Do you need to read a File into a String in Java ? This article will show two simple ways to achieve it. By the end of it, you will also learn the differences between each solution.
Solution #1 Use Files.readAllBytes
The first solution, which reads a file into an array of Bytes, uses the method Files.readAllBytes from a Path:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws IOException { String text = new String(Files.readAllBytes(Paths.get("myfile.txt"))); System.out.println(text); } }
Solution #2 Use Files.readString
The second solution, uses the method readString of the Files Class to read a File into a String
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class Main { public static void main(String[] args) throws IOException { String text = Files.readString(Path.of("myfile.txt")); System.out.println(text); } }
Comparing the two approaches
Both Files.readString
and new String(Files.readAllBytes(Paths.get("myfile.txt")))
can be used to read a file into a string in Java. However, there are some differences between the two approaches.
- Return Type:
Files.readString
returns the file content as aString
.Files.readAllBytes
returns the file content as abyte[]
, which is then converted to aString
using theString
constructor.
- Charset Encoding:
Files.readString
automatically detects the encoding of the file based on its content. It uses the default charset if the file encoding cannot be determined.Files.readAllBytes
reads the file content as a byte array without any charset encoding. It reads the raw bytes from the file.
- Convenience:
Files.readString
is a more convenient method as it directly returns the file content as aString
, eliminating the need for an additional conversion step.Files.readAllBytes
requires an extra step of converting the byte array to aString
using theString
constructor.
In terms of simplicity and conciseness, Files.readString
is generally considered more straightforward as it directly returns the file content as a String
without the need for additional conversions. However, if you require fine-grained control over the charset encoding or if you prefer working with raw bytes before converting them to a String
, then Files.readAllBytes
may be a better choice.