1public String readFile(String filePath) {
2 String result = "";
3 try {
4 result = Files.readString(Paths.get(filePath));
5 } catch (IOException e) {
6 e.printStackTrace();
7 }
8 return result;
9}
1public static String loadFileAsString(String path) {
2 InputStream stream = YourClassName.class.getResourceAsStream(path);
3 try {
4 String result = new String(stream.readAllBytes());
5 return result;
6 } catch (IOException e) {
7 e.printStackTrace();
8 return null;
9 }
10}
11
1import java.io.IOException;
2import java.nio.file.Files;
3import java.nio.file.Paths;
4
5public class ReadFileToString
6{
7 public static void main(String[] args)
8 {
9 String filePath = "c:/temp/data.txt";
10
11 System.out.println( readAllBytesJava7( filePath ) );
12 }
13
14 //Read file content into string with - Files.readAllBytes(Path path)
15
16 private static String readAllBytesJava7(String filePath)
17 {
18 String content = "";
19
20 try
21 {
22 content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
23 }
24 catch (IOException e)
25 {
26 e.printStackTrace();
27 }
28
29 return content;
30 }
31}
32