Java 8 – Reading a file as String
There are a lot of examples how to read a file content in Java 8.
The most common one is
1 2 3 4 5 6 7 |
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public static void main(String[] args) throws IOException { String content = new String(Files.readAllBytes(Paths.get("duke.java"))); } |
However, you can receive different results for the same file on different operation systems!
Use always a charset with String to Byte array transformations and vice versa to achieve a cross-platform identical output from this code section:
1 2 3 4 5 6 7 8 9 |
import java.io.IOException; import java.nio.file.*; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.ISO_8859_1; public static void main(String... args) throws IOException { String stringContent = new String(Files.readAllBytes(Paths.get("duke.java")), UTF_8); byte[] byteIso8859Content = stringContent.getBytes(ISO_8859_1); } |
Spelling error report
The following text will be sent to our editors: