If I print directly as
System.out.println("a\nb");
the result will be as expected, with a new line between characters, but if I read the same line from a text file using
public static void main(String[] args) throws IOException {
List<String> lines;
lines = Files.readAllLines(Paths.get("filename.txt"));
String[] array = lines.toArray(new String[0]);
System.out.println(array[0]);
the text displayed will be exactly as written in a file "a\nb" without a new line between the characters. toString and other methods do not help.
How should I update the code?
With the help of the colleagues and commenters got an explanation and an answer (not the most elegant approach though). "\n" in the code is interpreted as a new line character, but when read from a file it becomes a set of two characters: "\" and "n" and is no longer properly recognized. The shortest way to eliminate the problem would be to replace these characters with the new line in the code of the program, adding "replace("\n", "\n")". So, the code becomes as follows:
public static void main(String[] args) throws IOException {
List<String> lines;
lines = Files.readAllLines(Paths.get("filename.txt"));
String[] array = lines.toArray(new String[0]);
System.out.println(array[0].replace("\\n", "\n"));