java file get string content code example
Example: load contents of file into string java
package test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileToStringJava8 {
public static void main(String args[]) throws IOException {
InputStream is = new FileInputStream("manifest.mf");
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while(line != null){
sb.append(line).append("\n");
line = buf.readLine();
}
String fileAsString = sb.toString();
System.out.println("Contents (before Java 7) : " + fileAsString);
String contents = new String(Files.readAllBytes(Paths.get("manifest.mf")));
System.out.println("Contents (Java 7) : " + contents);
String fileString = new String(Files.readAllBytes(Paths.get("manifest.mf")), StandardCharsets.UTF_8);
System.out.println("Contents (Java 7 with character encoding ) : " + fileString);
Files.lines(Paths.get("manifest.mf"), StandardCharsets.UTF_8).forEach(System.out::println);
}
}