Credits

Monday, January 17, 2011

Java's Byte and Character Streams

Stream is a sequence of data flowing from source to destination.  And, we use streams whenever we have inputs and outputs from keyboard to monitor among others.

But, two types of streams include byte and character streams. Both are supported by java.io package and work with files. Byte stream allows 8 - bit data, represented by InputStreamReader and OutputStreamReader while Character stream works on 16-bit data, represented by Reader and Writer and deals mainly with character - oriented data.

The program below performs the same outputs but different in terms of streaming.
[+/-] show/hide


import java.io.*;
public class CopyBytes{
public static void main (String[] args) throws IOException{
FileInputStream in = null;
FileOutputStream out =null;
try{
in = new FileInputStream("C:\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\input.txt");
out = new FileOutputStream("C:\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\output.txt");
int c;
while ((c=in.read()) != -1){
out.write (c);
}
}finally {
if (in!=null){
in.close();
}
if (out!=null){
out.close();
}
}
}
}


import java.io.*;
public class CopyCharacters{
public static void main (String[] args) throws IOException{
FileReader inputStream = null;
FileWriter outputStream =null;
try{
inputStream = new FileReader("C:\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\input.txt");
outputStream = new FileWriter("C:\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\output.txt");
int c;
while ((c=inputStream.read()) != -1){
outputStream.write (c);
}
}finally {
if (inputStream!=null){
inputStream.close();
}
if (outputStream!=null){
outputStream.close();
}
}
}
}

AddThis