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.

8 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
  3. Use strong action verbs and stay away from general statements such as "has strong communications skills." Best Dissertation Writing Service

    ReplyDelete
  4. Advances in communications and technology have brought with it an off-shoot phenomenon that has greatly impacted the way individuals and businesses connect and deal with each other transfer files

    ReplyDelete

  5. Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
    https://forexbonus.xyz/

    ReplyDelete
  6. Ambra.Investments-Specialist provider of Outsourced portfolio mangement,customised equity portfolios,investment research,value investing,quantitative equity research,customised equity portfolios.
    outsourced investment research

    ReplyDelete
  7. I was reading your article and wondered if you had considered creating an ebook on this subject. Your writing would sell it fast. You have a lot of writing talent. welcher vpn anbieter

    ReplyDelete
  8. It is interesting to read your blog post and I am going to share it with my friends. aybabg

    ReplyDelete