0

Is there any way for java.util.Scanner to include the newline escape character when reading from a file?

This is my code:

File myFile = new File("file.txt");
Scanner myReader = new Scanner(myFile);
String content = "";
while(myReader.hasNextLine()) {

    content += myReader.nextLine();
}
System.out.println(content);
myReader.close();

When it reads from the file, it doesn't include '\n' or any new lines. Does anyone know how to do this?

Thanks

Caleb Shaw
  • 35
  • 4
  • 2
    Just append `\n` character to a variable after reading a line. If you really want to read as-is then use `nextByte()` function. – Whome Nov 07 '20 at 20:53
  • This subject was answered here ;) https://stackoverflow.com/questions/23312161/java-how-do-i-detect-n-characters-from-a-scanner-reading-from-a-file – manuel antunes Nov 07 '20 at 20:57
  • 1
    @manuelantunes - No, it hasn't been answered there. That question is: `How do I detect “\n” characters from a scanner reading from a file` whereas this question is: `Is there a way for Java Scanner to include '\n' when it is reading lines?` – Arvind Kumar Avinash Nov 07 '20 at 21:01
  • There is no "newline escape character", unless you're referring to the "\" in a string literal. Once a "\n" inside a string literal has been processed, there is only the newline character, and the "\n" sequence is gone. – NomadMaker Nov 07 '20 at 21:36

2 Answers2

0

When it reads from the file, it doesn't include '\n' or any new lines. Does anyone know how to do this?

You can add the new line explicitly as follows:

while(myReader.hasNextLine()) {
    content += myReader.nextLine() + "\n";
}

I also recommend you use StringBuilder instead of String for appending in a loop.

StringBuilder content = new StringBuilder();
while (myReader.hasNextLine()) {
    content.append(myReader.nextLine()).append(System.lineSeparator());
    // or the following
    // content.append(myReader.nextLine()).append('\n');
}

Check StringBuilder vs String concatenation in toString() in Java to learn more about it.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

If you you just want to read in lines and the line terminator you can do it by changing the behavior of Scanner.next(). If you run the following it will take in the line and the new line terminator as one unit.

  • \\z is a regex directive that says to include the line terminator.
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z");
for (int i = 0; i < 5; i++) {
    String line = scan.next();
    System.out.println(line + "on next line");
}

To read from a file, try this.

try {
    Scanner scan = new Scanner(new File("f:/Datafile.txt"));
    scan.useDelimiter("\\z");
    while (scan.hasNextLine()) {
        String line = scan.next();
        System.out.print(line);
    }
} catch (FileNotFoundException fe) {
    fe.printStackTrace();
}
WJS
  • 36,363
  • 4
  • 24
  • 39