Apr 4, 2017

Read and Write a File Line by Line in Java 8

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class FileTest {

 public static void main(String[] args) throws IOException  {
  
  Path pathToRead = Paths.get("C:\\...\\dataIn.csv");
  
  // Check if file exists
  if(!Files.exists(pathToRead)) {
   System.out.println("file doesn't exist :-(");
   return;
  };
  
  // read a file line by line
  Files.lines(pathToRead).forEach(line -> {
   // Process the String line here!!
   System.out.println(line);
  });
  
  // write a file line by line
  List<String> lines = Arrays.asList("line 1", "line 2", "line 3");
  Path pathToWrite = Paths.get("C:\\...\\dataOut.csv");
  Files.write(pathToWrite, lines);
 }
}

In Files.write() you can use also add Options, e.g. StandardOpenOption.CREATE or StandardOpenOption.APPEND. If omitted like above you get StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING.

More options to read/write also larger files in a buffered way are found here https://www.baeldung.com/java-read-file

3 comments: