Leave a Message To Me

Friday, May 28, 2010

Read from, and Write to, files in Java

import java.io.*;

public class test {
   public static void main (String [] args){
// Stream to write file
FileOutputStream fout;
   // Stream to read file
FileInputStream fin;
try
{
   // Open an output stream
   fout = new FileOutputStreama ("myfile.txt");

   // Print a line of text
   new PrintStream(fout).println ("hello world!");
                     // then read from the file
   fin = new FileInputStream ("myfile.txt");
   System.out.println( new DataInputStream(fin).readLine() );
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write/read to file");
System.exit(-1);
}  

  }
}

0 comments: