Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reading Entire File into String in Java http://www.chankok.com/java-read-entire-file-into-string/
package com.chankok.io;
import java.io.FileReader;
import java.io.IOException;
public class Java6ReadEntireFileExample {
public static void main(String[] args) {
FileReader fr = null;
try {
StringBuilder sb = new StringBuilder();
// Create an input stream
fr = new FileReader("C:\\test-read-entire-file-into-string.txt");
int data;
// Read a character and append it to string builder one by one
while ((data = fr.read()) != -1) {
sb.append((char) data);
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Close the input stream
if (fr != null) fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.chankok.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Java7ReadEntireFileExample {
public static void main(String[] args) {
try {
// Create a file path of the file
Path filePath = Paths.get("C:\\test-read-entire-file-into-string.txt");
// Reading all bytes in a file into a string
String stringData = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
System.out.println(stringData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.chankok.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class Java8ReadEntireFileExample {
public static void main(String[] args) {
try {
// Create a file path of the file
Path filePath = Paths.get("C:\\test-read-entire-file-into-string.txt");
// Reading and joining all lines in a file into a string
String stringData = Files.lines(filePath, StandardCharsets.UTF_8)
.collect(Collectors.joining("\n"));
System.out.println(stringData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment