Home > OS >  Handling Special Characters: '\n', '\\n', '\t' and '\\t
Handling Special Characters: '\n', '\\n', '\t' and '\\t

Time:10-30

I have a text file named myfile with one line text, containing some specials characters \n (new line character) or some escaped of this characters \\n,

myfile content:

thiss is\n a string\\n bla bla

I want to read this file but keep the semantic meaning of these special characters.

I tried to read the file without any special work, but all these special characters are interpreted as a raw string.

public class Main {
    public static void main(String[] args) {

        String path = Main.class.getResource("/myfile").getPath();
        try (BufferedReader in = new BufferedReader( new FileReader(path))) {
            String line = in.readLine();
            System.out.println(line); // printed as a raw string, `\n` not interpreted as a new line char
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

I also tried using the String.replace() method, but it only works for \n but not for \\n.

line.replace("\\n", "\n");

CodePudding user response:

Try this.

public static void main(String[] args) throws IOException {
    String in = "thiss is\\n a st\\tring\\\\n bla bla";
    String out = in
        .replaceAll("(?<!\\\\)\\\\n", "\n")
        .replaceAll("(?<!\\\\)\\\\t", "\t")
        .replaceAll("\\\\\\\\", "\\\\");
    System.out.println("in  : "   in);
    System.out.println("out : "   out);
}

output:

in  : thiss is\n a st\tring\\n bla bla
out : thiss is
 a st   ring\n bla bla

CodePudding user response:

You can actually do:

line = line.replace("\\\\n", "\n");
line = line.replace("\\n", "\n");

in that order.

  •  Tags:  
  • java
  • Related