In these examples, we take a look at how to convert a file to String in various Java versions.
Example 1: Java 7 or belowpackage org.code2care.java.examples;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Java7FileToStringExample {
public static void main(String[] args) {
File textFile = new File("c:/data/myfile.txt");
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(textFile))) {
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator());
}
String fileToString = stringBuilder.toString();
System.out.println(fileToString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example 2: Java 8 or above
You can make use of the improved Java 8 Files class to make you code look more cleaner and shorter to perform the same operation.
package org.code2care.java.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Java8FileToStringExample {
public static void main(String[] args) throws IOException {
Path txtFilePath = Path.of("c:/data/myfile.txt");
String fileToString = new String(Files.readAllBytes(txtFilePath));
System.out.println(fileToString);
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!