Credits

Saturday, August 7, 2010

Maximizing Java Streams

Streams in Java are used to course through data from a source like keyboard or file among others to a destination like monitor, printer or file to name a few.

A stream can either be a byte or character stream; ideally, if you wont work on images or sounds, typical inputs of text can work well with character streams.


You can associate a file class with your stream class  to work either as the source or destination. Find below the sample program.

[+/-] show/hide

/*prints from a given file to an output stream*/
import java.io.*;

public class ReadFromToStream {

public static void main (String[] args) throws IOException{
//InputStream istream;
InputStream fstream;
OutputStream ostream;
int c;
File fromFile=new File("\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\data.txt");
ostream=System.out;
fstream=new FileInputStream(fromFile);
try{

while ((c=fstream.read()) != -1){
ostream.write (c);
}
}catch (IOException e)
{System.out.println("Error :"+e.getMessage());}
finally {
fstream.close();
ostream.close(); }
}
}


AddThis