Friday, January 14, 2011

Sample Program on Java's Streams

In my earlier post, streams are used to show a sequence of data flow from source to destination. Streams can be bytes or character and they can be sourced from a keyboard or file to monitor, printer or file again to name a few.

Find below a sample program that copies text from source file, data.txt, to destination file, output.txt.  The program below uses write() to copy the character of data.txt until it reaches end of file.
[+/-] show/hide

/*reading from a file*/
public class ReadFromFile{
public static void main (String[] args) throws IOException{
InputStream istream;
OutputStream ostream;
int c;
File inFile=new File("\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\data.txt");
File outFile=new File("\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\output.txt");
istream= new FileInputStream(inFile);
ostream=new FileOutputStream(outFile);

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

No comments: