How to read and write files in Java 8

This tutorial presents the different options available to read and write files in Java .

Reading files

Using  FileInputStream and BufferedReader

In the following example we will create a BufferedReader from InputStreamReader. Use this option when you need to read byte streams and transform them into character streams. You can specify the encoding charset.  Examples : Reading a zip file, image, network resources, or simply text files etc.

File file = new File("myFile.zip");
try {
  FileInputStream fis = new FileInputStream(file);
  BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  String line;
  while((line=br.readLine())!=null){
    System.out.println(line);
  }
  br.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when reading the file
  e.printStackTrace();
}

 

Using FileReader and BufferedReader

This example is similar the previous one, except the fact that we build the BufferedReader from a FileReader.

Use this option when you have to read character based content. You cannot specify the encoding charset for this method and it will use the platform encoding.

File file = new File("myFile.txt");
try {
  BufferedReader br = new BufferedReader(new FileReader(file));
  String line;
  while((line=br.readLine())!=null){
    System.out.println(line);
  }
  br.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when reading the file
  e.printStackTrace();
}

 

Using Files.newBufferedReader() in Java 7 and above

This example is similar to the first one (Using FileInputStreamAND BufferedReader) .  It uses the java.nio package and the try-with-resources exception management structure. It works starting from java 7.

The necessary imports

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

The code

Path path = Paths.get("c:/tmp/myfile.csv");
Charset charset = Charset.forName("UTF-8");
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
  String line = null;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException e) {
  e.printStackTrace();
}

 

Using Lambda expression in Java 8

One of the benefits of Lambda Expression is the reduction of the number of lines of code. In this example, we will read and print the content of a file in one line using Lambda Expressions and java.nio.file.Files class :

Files.lines(new File("c:/myfile.txt").toPath()).forEach(System.out::println);

(for simplicity we didn’t include the exception management for the IOException exception)

Writing files

Using FileOutputStream

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  bw.write("Write somthing to the file ...");
  bw.newLine();
  bw.close();
} catch (FileNotFoundException e){
  // File was not found
  e.printStackTrace();
} catch (IOException e) {
  // Problem when writing to the file
  e.printStackTrace();
}

 

Using FileWriter

You better use FileWriter or PrintWriter if you plan to write some character based content or a text file.

try {
  FileWriter fw = new FileWriter("myOutFile.txt");
  fw.write("Example of content");
  fw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

 

Using PrintWriter

Similar to FileWriter but with some specifities. Here is the Oracle’s PrintWriter definition:

Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

try {
  PrintWriter pw = new PrintWriter("myOutFile.txt");
  pw.write("Example of content");
  pw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

 

Using OutputStreamWriter

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  osw.write("Soe content ...");
  osw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

 

 

You like this content ? Share it with you entourage !

Leave a Reply

Your email address will not be published.