1package test;
2
3import java.io.BufferedReader;
4import java.io.FileInputStream;
5import java.io.IOException;
6import java.io.InputStream;
7import java.io.InputStreamReader;
8import java.nio.charset.StandardCharsets;
9import java.nio.file.Files;
10import java.nio.file.Paths;
11
12
13/**
14 * Java Program to demonstrate different ways to loop over collection in
15 * pre Java 8 and Java 8 world using Stream's forEach method.
16 * @author Javin Paul
17 */
18public class FileToStringJava8 {
19
20 public static void main(String args[]) throws IOException {
21
22 // How to read file into String before Java 7
23 InputStream is = new FileInputStream("manifest.mf");
24 BufferedReader buf = new BufferedReader(new InputStreamReader(is));
25
26 String line = buf.readLine();
27 StringBuilder sb = new StringBuilder();
28
29 while(line != null){
30 sb.append(line).append("\n");
31 line = buf.readLine();
32 }
33
34 String fileAsString = sb.toString();
35 System.out.println("Contents (before Java 7) : " + fileAsString);
36
37
38 // Reading file into Stirng in one line in JDK 7
39 String contents = new String(Files.readAllBytes(Paths.get("manifest.mf")));
40 System.out.println("Contents (Java 7) : " + contents);
41
42
43
44 // Reading file into String using proper character encoding
45 String fileString = new String(Files.readAllBytes(Paths.get("manifest.mf")), StandardCharsets.UTF_8);
46 System.out.println("Contents (Java 7 with character encoding ) : " + fileString);
47
48
49 // It's even easier in Java 8
50 Files.lines(Paths.get("manifest.mf"), StandardCharsets.UTF_8).forEach(System.out::println);
51
52 }
53
54
55}
56