Java · Java8

File Reading Using Java8 Streams

Here we can use Java8 streams to read a file content.

/**
 * 
 */
package java8pract.streams;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author prabhu kvn
 *
 */
public class StreamsInIO {

 /**
 * Using Java8 Streams to read the file
 */
 public StreamsInIO() {
 // TODO Auto-generated constructor stub
 }

 /**
 * @param args
 */
 public static void main(String[] args) {

 try {
 FileReader freader = new FileReader(new File("d:/text1.txt"));
 BufferedReader bReader = new BufferedReader(freader);
 Stream fileStream = bReader.lines();
 List fileContent = fileStream.collect(Collectors.toList());
 System.out.println(fileContent.size());
 System.out.println(fileContent);

 } catch (FileNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

 }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s