Thompson Aniyo
Thompson Aniyo

Reputation: 1

How to read “\n” text in file as a newline?

My text file contains this 1 line

This line is used for testing.\nTesting testing testing.

And this is how I read that line in Java

import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

class Main {
  public static void main(String[] args) {
    List<String> list = null;
      try {
            list = Files.readAllLines(Paths.get("path to txt file"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] Array = list.toArray(new String[list.size()]);
  }
}

And when I print it out with System.out.print(Array[0]); I get this as a result: This line is used for testing.\nTesting testing testing.

I want the result to be like this:

This line is used for testing.

Testing testing testing.

Upvotes: 0

Views: 1693

Answers (2)

RUARO Thibault
RUARO Thibault

Reputation: 2850

If you want such behavior, the best way is to implement this in your code:

list = Files.readAllLines(Paths.get(""))
                    .stream()
                    .flatMap(line -> Arrays.stream(line.split("\\\\n")))
                    .collect(Collectors.toList());

This read the files, like you did, plus it interprets the \n to give you new Lines every time.

That's the only way I've found

Upvotes: 0

SevvyP
SevvyP

Reputation: 385

Typing \n in a text file doesn't give you a newline, it gives you the individual characters \ and n. If you want to add a newline and have your program print out the text with that newline, you'll have to actually insert a newline (ie. press enter).

If you want to make your program be able to understand escaped characters (process \n as a newline), you'd have to add that logic yourself. The simplest way would be to iterate over each character and if a character is \, process according to the next character. In your case, once you see \ followed by n, delete those two characters and insert a newline in their place.

Upvotes: 0

Related Questions