Creating, Writing, Reading files using Java Files API of Java 7

In our previous post we did get a taste of the power of the static APIs in the Java Files class and we managed to compare the code written without using the APIs in Java Files and with using the APIs in Java Files.

also read:

In this post let me delve further into the other APIs offered by Java Files class and look at the creation, deletion of files and reading and writing to the files.

Creating and Deleting a file:

//Create a new Path
Path newFile = Paths.get("test1");
try {
  Files.deleteIfExists(newFile);
  newFile = Files.createFile(newFile);
} catch (IOException ex) {
  System.out.println("Error creating file");
}
System.out.println(Files.exists(newFile));

Creating a new Pathobject doesn’t create a file on the file system. A Path object just indicates a file/directory or any other resource location. The resource might or might not be present in the identified location.

Writing to the file using BufferedWriter:

In the above code we create a file, which contains no data. Lets now write something to the file:

//Writing to file4
try(BufferedWriter writer = Files.newBufferedWriter(
        newFile, Charset.defaultCharset())){
  writer.append("This is first line");
  writer.newLine();
  writer.append("This is second line");
  writer.newLine();
  writer.append("This is third line");
  writer.newLine();
  writer.flush();
}catch(IOException exception){
  System.out.println("Error writing to file");
}

The interesting piece from the above code is:

try(BufferedWriter writer = Files.newBufferedWriter(
        newFile, Charset.defaultCharset())){

where we make use of the static API newBuffredWriter in Java Files to obtain the BufferedWriter for the file. And also we make use of the try-with-resources construct to get rid of the finally clause.

Reading from the file using BufferedReader:

Now that we have some content in the file, lets read the content back and display it on the console.

//Reading from file
try(BufferedReader reader = Files.newBufferedReader(
        newFile, Charset.defaultCharset())){
  String lineFromFile = "";
  System.out.println("The contents of file are: ");
  while((lineFromFile = reader.readLine()) != null){
    System.out.println(lineFromFile);
  }

}catch(IOException exception){
  System.out.println("Error while reading file");
}

We ended up making use of the static API newBufferedReader to read the contents of the file and print it on the console.

The advantage of using the Java Files API is that the code is more readable than before and also the parts of the code encapsulated by the API can be reusable.

Here is the complete code for the above example:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class NewFilesApiTest {
  public static void main(String[] args)  {

    //Creating a new file
    Path newFile = Paths.get("test1");
    try {
      Files.deleteIfExists(newFile);
      newFile = Files.createFile(newFile);
    } catch (IOException ex) {
      System.out.println("Error creating file");
    }
    System.out.println(Files.exists(newFile));

    //Writing to file
    try(BufferedWriter writer = Files.newBufferedWriter(
            newFile, Charset.defaultCharset())){
      writer.append("This is first line");
      writer.newLine();
      writer.append("This is second line");
      writer.newLine();
      writer.append("This is third line");
      writer.newLine();
      writer.flush();
    }catch(IOException exception){
      System.out.println("Error writing to file");
    }

    //Reading from file
    try(BufferedReader reader = Files.newBufferedReader(
            newFile, Charset.defaultCharset())){
      String lineFromFile = "";
      System.out.println("The contents of file are: ");
      while((lineFromFile = reader.readLine()) != null){
        System.out.println(lineFromFile);
      }

    }catch(IOException exception){
      System.out.println("Error while reading file");
    }
  }

}

The output is:

true
The contents of file are:
This is first line
This is second line
This is third line

Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.

Comments

comments

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Trackbacks

  1. JavaPins says:

    Creating, Writing, Reading files using Java Files API of Java 7…

    Thank you for submitting this cool story – Trackback from JavaPins…

  2. [...] is the Path class. And I have used this class extensively in my posts about Files API here and here and also about WatchService [...]

  3. […] the concepts in a practical example, where we have the following situation: Our method attempts to write a file in a folder A, but if some error occurs an IOException (Checked Exception) is thrown and we will […]

Speak Your Mind

*