This has to do with character encoding. Computers only deal with numbers. To store text, the characters in the text have to be converted to and from numbers, using some scheme. That scheme is called the character encoding. There are many different character encodings; some of the well-known standard character encodings are ASCII, ISO-8859-1 and UTF-8.
In the first example, you read all the bytes (numbers) in the file and then convert them to characters by passing them to the constructor of class String
. This will use the default character encoding of your system (whatever it is on your operating system) to convert the bytes to characters.
In the second example, where you use Files.lines(...)
, the UTF-8 character encoding will be used, according to the documentation. When a sequence of bytes is found in the file that is not a valid UTF-8 sequence, you'll get a MalformedInputException
.
The default character encoding of your system may or may not be UTF-8, so that can explain a difference in behaviour.
You'll have to find out what character encoding is used for the file, and then explicitly use that. For example:
String content = new String(Files.readAllBytes(Paths.get("_template.txt")),
StandardCharsets.ISO_8859_1);
Second example:
Stream<String> lines = Files.lines(Paths.get("_template.txt"),
StandardCharsets.ISO_8859_1);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…