• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

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

June 20, 2012 //  by Mohamed Sanaulla//  Leave a Comment

Introduction to Java File API

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:

  • Java 7.0 Tutorials
  • New Features in Java 7.0
  • G1 Garbage Collector in Java 7.0

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 Java file APIs.

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.

Category: JavaTag: java 7

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.

Previous Post: « New features in JDBC 3.0
Next Post: Creating JSON using Groovy »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact