Reading and Writing Files

  • FileInputStream and FileOutputStream are the most often classes used to read and write the files in java which takes the file name as an argument to it's constructor as follows:

FileInputStream(String fileName) throws FileNotFoundException

FileOutputStream(String fileName) throws FileNotFoundException

  • fileName- specifies the name of the file that you want to open.
  • For an InputStream if the file does not exist, then FileNotFoundException is thrown.
  • For output streams, if the file cannot be opened or created , then FileNotFoundException is thrown.
  • We have to close a file when it done using close() method which is implemented by both FileInputStream and FileOutputStream.

void close( ) throws IOException

  • Failure of close() occurs because of “memory leaks” because of unused resources remaining allocated.
  • To read from a file we can use read( ) that is defined within FileInputStream.

int read( ) throws IOException

  • it reads a single byte from the file and returns the byte as an integer value. read( ) returns –1 when the end of the file is encountered.
/* Display a text file.
 To use this program, specify the name
 of the file that you want to see.
 For example, to see a file called TEST.TXT,
 use the following command line.
 java ShowFile TEST.TXT
*/
import java.io.*;
public class ShowFile 
{
 public static void main(String args[])
 {
 int i;
 FileInputStream fin;
 // First, confirm that a filename has been specified.
 if(args.length != 1) {
 System.out.println("Usage: ShowFile filename");
 return;
 }
 // Attempt to open the file.
 try {
 fin = new FileInputStream(args[0]);
 } 
 catch(FileNotFoundException e) 
 {
 System.out.println("Cannot Open File");
 return;
 }
 // At this point, the file is open and can be read.
 // The following reads characters until EOF is encountered.
 try
 {
 do 
 {
 i = fin.read();
 if(i != -1) System.out.print((char) i);
 } while(i != -1);
 } 
 catch(IOException e) 
 {
 System.out.println("Error Reading File");
 }
 // Close the file.
 try 
 {
 fin.close();
 }
 catch(IOException e)
 {
 System.out.println("Error Closing File");
 }
 }
}

We can close a file in a finally block which makes sure to close the file after try block execution as follows

try 
{
 do 
 {
 i = fin.read();
 if(i != -1) System.out.print((char) i);
 } while(i != -1);
} 
 catch(FileNotFoundException e)  //which catches when there is no such file which is the subclass of IOException
 {
 System.out.println("File Not Found.");
 }
catch(IOException e) 
{
 System.out.println("Error Reading File");
} finally 
{
 // Close file on the way out of the try block.
 try 
 {
 if(fin != null)
 fin.close();
 } catch(IOException e) {
 System.out.println("Error Closing File");
 }
}

To write to a file,we can use the write( ) method defined by FileOutputStream. Its simplest form is

void write(int byteval) throws IOException

/* Copy a file.
 To use this program, specify the name
 of the source file and the destination file.
 For example, to copy a file called FIRST.TXT
 to a file called SECOND.TXT, use the following
 command line.
 java CopyFile FIRST.TXT SECOND.TXT
*/
import java.io.*;
public class CopyFile 
{
 public static void main(String args[]) throws IOException
 {
 int i;
 FileInputStream fin = null;
 FileOutputStream fout = null;

 // First, confirm that both files have been specified.

 if(args.length != 2) 
 {
 System.out.println("Usage: CopyFile from to");
 return;
 }

 // Copy a File.
 try 
 {
  // Attempt to open the files.
 fin = new FileInputStream(args[0]);
 fout = new FileOutputStream(args[1]);
  do 
  {
 i = fin.read();
 if(i != -1) fout.write(i);
 } while(i != -1);
  } 
  catch(IOException e) 
  {
 System.out.println("I/O Error: " + e);
  } 
  finally 
  {
  try 
  {
 if(fin != null) fin.close();
  } 
  catch(IOException e2) 
  {
 System.out.println("Error Closing Input File");
 }
  try 
  {

 if(fout != null) 
 fout.close();
  } 
  catch(IOException e2) 
  {
 System.out.println("Error Closing Output File");
 }
 }
 }
}

Automatically Closing a File

  • JDK 7 added a new feature that offers another way to manage resources, such as file streams, by automating the closing process.
  • This is called as automatic resource management, or ARM which is the expand version of the try statement.
  • The main advantage of this is to avoid memory leaks by closing the files which are not in use which is done by try statement as follows

    try (resource-specification)

{

// use the resource

}

  • resource-specification is a statement that declares and initializes a resource, such as a file stream.
  • This new form of try is called the try-with-resources statement.

  • This can be used only if those resources implements AutoClosable interface which is extended by the b interface from java.lang package.

/* This version of the ShowFile program uses a try-with-resources
 statement to automatically close a file after it is no longer needed.
 Note: This code requires JDK 7 or later.
*/
import java.io.*;
public class ShowFile 
{
 public static void main(String args[])
 {
 int i;
 // First, confirm that a filename has been specified.
 if(args.length != 1) 
 {
 System.out.println("Usage: ShowFile filename");
 return;
 }

 // The following code uses a try-with-resources statement to open
 // a file and then automatically close it when the try block is left.
 try(FileInputStream fin = new FileInputStream(args[0]))  //this will automatically closes the file
 {
 do 
 {
 i = fin.read();
 if(i != -1) System.out.print((char) i);
 } while(i != -1);
 } 
 catch(FileNotFoundException e)
  {
 System.out.println("File Not Found.");
 } 
 catch(IOException e) 
 {
 System.out.println("An I/O Error Occurred");
 }
 }
}

results matching ""

    No results matching ""