Pages

How to write and read files in Java?

Question

How can I write to and read from files in Java?

Answer 

Java applications have access to local files. It means that it can read and write to files. Let's take a look at two simple applications that write lines of text and read it back.

Application one:

import java.io.*;

public class WriteFile
{
 
 public static void main (String args[]) //entry point
 {
  // FileOutputStream object
  FileOutputStream fout;  

  try
  {
      // Open an output stream
      fout = new FileOutputStream ("myfile.txt");

      // Print a line of text
      new PrintStream(fout).println ("This is simple application to write lines of text. Pretty Cool!!");

      // Close our output stream
      fout.close();  
  }
  // Catches any error conditions
  catch (IOException e)
  {
   System.err.println ("There were some errors writing lines.");
   System.exit(-1);
  }
 } 
}

The above code creates a FileOutputStream and writes a line of text to a file called myfile.txt. We must enclose the writing of file with try{...}catch block to trap or catch any exception that may occur.

Reading files in Java is easy as well. The code below creates FileInputStream to read file and display it to the user.

Application Two:

import java.io.*;

public class ReadFile
{
 // Main method
 public static void main (String args[])
 {
  // FileInputStream to read file
  FileInputStream fin;  

  try
  {
      // Open an input stream
      fin = new FileInputStream ("myfile.txt");

      // Read a line of text
      System.out.println( new DataInputStream(fin).readLine() );

      // Close our input stream
      fin.close();  
  }
  // Catches any error conditions
  catch (IOException e)
  {
   System.err.println ("Unable to read lines from file");
   System.exit(-1);
  }
 } 
}


No comments:

Post a Comment