Reading InputStream Into String With Java 8

Example below shows use of streaming with java 8.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.stream.Collectors;

public class IOTest {

	public static void main(String[] args) throws Exception {

		Path path = Paths.get("c:\\bharat\\temp\\cm15DEC2017bhav.csv");
		System.out.println(Files.exists(path));

		try (InputStream stream = Files.newInputStream(path, StandardOpenOption.READ)) {

			String allTextFromFile = read(stream);
			System.out.println(allTextFromFile);
		}

	}

	/** Reads all lines from file and returns a huge string */
	public static String read(InputStream input) throws IOException {
		try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
			return buffer.lines().collect(Collectors.joining("\n"));
		}
	}
}

Advertisements
  1. Leave a comment

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: