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.

2 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete
  2. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    Java Training in Chennai

    Java Training in Bangalore

    ReplyDelete