rewrite-migrate-java
rewrite-migrate-java copied to clipboard
Java 11: use `Files.readString` to read a file to a String
There are many patterns to read all the contents of a File
to a String
All the methods below will throw OOM if the file is larger than the available memory
// Java 7
String content = new String(Files.readAllBytes(Paths.get("file.txt")), StandardCharsets.UTF_8)`
// Using Guava
import com.google.common.base.Charsets;
import com.google.common.io.Files;
String text = Files.toString(new File(path), Charsets.UTF_8);
// Using Files.readAllBytes
Path filePath = Path.of("file.txt");
String fileContent = "";
try
{
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
fileContent = new String (bytes);
}
catch (IOException e)
{
e.printStackTrace();
}
// Using BufferedReader (Java 6)
Path filePath = Path.of("file.txt");
String fileContent = "";
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null)
{
contentBuilder.append(sCurrentLine).append("\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
fileContent = contentBuilder.toString();
// Using Commons IO
File file = new File("file.txt");
String content = FileUtils.readFileToString(file, "UTF-8");
// Using the Scanner class
File file = new File("file.txt");
StringBuilder fileContents = new StringBuilder();
try (Scanner scanner = new Scanner(file)) {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + System.lineSeparator());
}
}
// Using the Scanner class with String concatenation
File file = new File("file.txt");
String fileContents = ""
try (Scanner scanner = new Scanner(file)) {
while(scanner.hasNextLine()) {
fileContents = fileContents + System.lineSeparator());
}
}
Starting with Java 11, all the patterns above could be replaced with
Path filePath = Path.of("file.txt");
String content = Files.readString(fileName);