Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.4. Working with files

5.4. Working with files
Last updated: 23 January 2013.

This tutorial will show you how to read and write text and binary files in Java with the classes provided by the package java.io.

The Java API provides classes to read and write files that can be either text files or binary files. You can find many classes for reading and writing files in the java.io package, allowing you to achieve a given task in many ways. In order to avoid cluttering this page, only one example is given for each task in this tutorial. Please refer to the Java API documentation for more examples.

You might also be interested in reading documentation about the package java.nio (New I/O) which was introduced with J2SE 1.4, in particular to add high performance I/O classes to the Java API. In fact, the package java.io will meet your needs for common tasks related with files but if you are doing intensive I/O operations and face performance issues, take a look at the package java.nio.


5.4.1. How to read a text file

Several classes are provided by the Java API, such as BufferedReader, FileReader, LineNumberReader, Scanner and InputStreamReader. The class FileTesting shown below contains a single method named readFile(String filePath) that reads the lines of a text file and prints them to the standard output using the BufferedReader class. The method readFile(String filePath) takes as an argument the path of the file to be read.

A path looks something like this for Windows users:

C:\MyDirectory\MyTextFile.txt

For Linux users, a path looks like this:

/home/myName/MyDirectory/MyTextFile.txt.


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public final class FileTesting {

   
public void readFile(String filePath){

         
BufferedReader reader = null;

         
try{
               
reader = new BufferedReader(new FileReader(filePath));

                String line = reader.readLine
();

               
while(line != null){
                     
System.out.println(line);
                      line = reader.readLine
();
               
}
          }
         
catch(FileNotFoundException e){
               
System.out.println("A FileNotFoundException has been thrown");
                e.printStackTrace
();
         
}
         
catch(IOException e){
               
System.out.println("An IOException has been thrown");
                e.printStackTrace
();
         
}
         
finally{
               
if(reader != null){
                     
try{
                           
reader.close();
                     
}
                     
catch(IOException e){
                           
e.printStackTrace();
                     
}
                }
          }
    }

}

I could have used the class FileReader alone to read from the text file but I passed a FileReader object to the constructor of the class BufferedReader in order to increase performance. In fact, I wrapped a BufferedReader object around a FileReader object because the BufferedReader object maintains a buffer containing input from the text file. That buffer is created when the constructor of the class BufferedReader is called. Then when the method readLine is invoked, instead of reading from the physical text file, it reads from the buffer, which is much faster. Generally, the classes of the Java API that deal with files and whose names start with "Buffered" maintain a buffer.

As you can see, the exceptions FileNotFoundException and IOException are caught in the method readFile(String filePath). As they are checked exceptions, they must be handled somewhere in the call stack at compile time. The class App shown below calls the method readFile(String filePath). As you can see, I'm passing "MyTextFile.txt" instead of its complete path name (which includes the parent directories) because passing the complete path is not necessary if the file to be read is in the current directory.

public final class App {

   
public static void main(String[] args) {
         
new FileTesting().readFile("MyTextFile.txt");
   
}

}


5.4.2. How to write to a text file

You can choose from several classes such as BufferedWriter, FileWriter, OutputStreamWriter and PrintWriter. The method writeFile shown below simply writes two lines of text to a file named MyTextFile.txt using the class BufferedWriter:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public final class FileTesting {

   
public void writeFile(){

         
BufferedWriter writer = null;

         
try{
               
writer = new BufferedWriter(new FileWriter("MyTextFile.txt", true));

                writer.write
("First line");
                writer.newLine
();
                writer.write
("Second line");

                writer.flush
();
         
}
         
catch(IOException e){
               
e.printStackTrace();
         
}
         
finally{
               
if(writer != null){
                     
try{
                           
writer.close();
                     
}
                     
catch(IOException e){
                           
e.printStackTrace();
                     
}
                }
          }
    }

}


5.4.3. How to write to a binary file

The following classes of the Java API allow writing to a binary file: BufferedOutputStream, ByteArrayOutputStream, DataOutputStream, FileOutputStream, ObjetOutputStream, PrintStream and RandomAccessFile. Note that the class RandomAccessFile can also be used for reading a binary file. The method writeFile shown below simply writes 3 bytes to a binary file:

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public final class FileTesting {

   
public void writeFile(){

         
BufferedOutputStream out = null;

         
try{
               
out = new BufferedOutputStream(new FileOutputStream("MyFile.bin"));

               
byte[] byteArray = { (byte)0, (byte)1, (byte)2 }; // an array of 3 bytes

               
out.write(byteArray);
         
}
         
catch(IOException e){
               
e.printStackTrace();
         
}
         
finally{
               
if(out != null){
                     
try{
                           
out.close();
                     
}
                     
catch(IOException e){
                           
e.printStackTrace();
                     
}
                }
          }
    }

}


5.4.4. How to read a binary file

Depending on your needs, you can choose from several classes such as BufferedInputStream, ByteArrayInputStream, DataInputStream, FileInputStream, ObjectInputStream or RandomAccessFile. The method readFile(String filePath) shown below reads a binary file into an array of bytes and prints each byte to the standard output:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public final class FileTesting {

   
public void readFile(String filePath){

         
BufferedInputStream in = null;

         
try{
               
in = new BufferedInputStream(new FileInputStream("MyFile.bin"));

               
int availableBytes = in.available();

               
byte[] byteArray = new byte[availableBytes];

               
while(in.read(byteArray) != -1){
                     
for(byte b : byteArray)
                           
System.out.println(b);
               
}
          }
         
catch(IOException e){
               
e.printStackTrace();
         
}
         
finally{
               
if(in != null){
                     
try{
                           
in.close();
                     
}
                     
catch(IOException e){
                           
e.printStackTrace();
                     
}
                }
          }
    }

}


5.4.5. The class File

An instance of the class File can be seen as a representation of a file or directory that may or may not exist. The class File provides methods that return information about existing files and directories. It also provides methods to create, delete, rename and change the read/write permissions of files and directories. As an example, the method listDirectory(String directoryPathName) shown below prints to the standard output the names of all the files contained in a given directory:

import java.io.File;

public final class FileTesting {

   
public void listDirectory(String directoryPathName){

         
File directory = new File(directoryPathName);

         
if(! directory.exists()){
               
System.out.println("The directory " + directoryPathName + " does not exist");
               
return;
         
}

         
if(! directory.isDirectory()){
               
System.out.println(directoryPathName + " is not a directory");
               
return;
         
}

         
if(! directory.canRead()){
               
System.out.println(directoryPathName + " cannot be read");
               
return;
         
}

         
File[] list = directory.listFiles();

         
for(File f : list){
               
if(f.isFile()){ // only print the names of files and omit the subdirectories
                     
System.out.println(f.getName());
               
}
          }
    }

}


5.4.6. Code exercise

Write a method named copy(String sourceFilePath, String targetFilePath) that copies a source text file to a target text file using the classes BufferedReader and BufferedWriter. If the target text file already exists, the method copy(String sourceFilePath, String targetFilePath) must return without overwriting the existing target text file.


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public final class FileTesting {

   
public void copy(String sourceFilePath, String targetFilePath){

         
BufferedReader reader = null;
          BufferedWriter writer =
null;

         
try{
               
File source = new File(sourceFilePath);
                File target =
new File(targetFilePath);

               
if(! source.exists()){
                     
System.out.println(sourceFilePath + " does not exist");
                     
return;
               
}

               
if(! source.canRead()){
                     
System.out.println(source + " cannot be read");
                     
return;
               
}

               
if(target.exists()){
                     
System.out.println(target + " already exists");
                     
return;
               
}

               
reader = new BufferedReader(new FileReader(source));
                writer =
new BufferedWriter(new FileWriter(target));

               
for(String line = reader.readLine(); line != null; line = reader.readLine()){
                     
writer.write(line);
                      writer.newLine
();
               
}

          }
         
catch(IOException e){
               
e.printStackTrace();
         
}
         
finally{
               
try{
                     
if(reader != null)
                           
reader.close();
                     
if(writer != null)
                           
writer.close();
               
}
               
catch(IOException e){
                     
e.printStackTrace();
               
}
          }
    }

}


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.4. Working with files
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.5. Working with dates

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7