Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Handling Special Characters: '\n', '\\n', '\t' and '\\t' when reading a file in java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading