2

This is my code, I am trying to write a text file replacing "Up" and "Right" with ↑ and →. The problem is that the text file output is: "→ ↑"(this is not what i wanted) and the console output is "↑ →".

private static void print(String t){
    File log = new File("a.txt");
    String raw = t;
    raw = raw.replaceAll("Up", " \u2191 ");     //↑
    raw = raw.replaceAll("Right", " \u2192 ");  //→

    try{
        FileWriter fileWriter = new FileWriter(log, true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(raw + "\n");
        System.out.println(raw + "\n")
        bufferedWriter.close();

    }catch(IOException e) {}
}

I think it may be an encoding error, but I dont know how to fix it.

beeb
  • 1,615
  • 1
  • 12
  • 24
Sapu
  • 81
  • 1
  • 3
  • 10
  • Maybe you can find your answer here : https://stackoverflow.com/questions/4597749/read-write-txt-file-with-special-characters?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Azalkor Apr 19 '18 at 12:43
  • Possible duplicate of [Default character encoding for java console output](https://stackoverflow.com/questions/24803733/default-character-encoding-for-java-console-output) – Alex Shesterov Apr 19 '18 at 12:43
  • 1
    Possible duplicate of [Java BufferedWriter object with utf-8](https://stackoverflow.com/questions/6998905/java-bufferedwriter-object-with-utf-8) – Michael Apr 19 '18 at 12:44
  • 1
    *Never* write an empty catch block. If something goes wrong, you want to know about it. At the very least, put `e.printStackTrace();` in there. As I commented on [your previous question about the same issue](https://stackoverflow.com/questions/49886402/how-can-i-print-symbols-from-a-string-to-a-txt-file), you are writing your file with the UTF-8 encoding, then reading it using a tool that assumes a one-byte encoding, such as the Windows-125x encodings. Notepad is an example of such a tool. Use a UTF-8 capable viewer to examine the file. – VGR Apr 19 '18 at 13:43

1 Answers1

0

First of all, it's best to specify the encoding (you probably want UTF-8) before you write your file.

private static void print(String t){
    File log = new File("a.txt");
    String raw = t;
    raw = raw.replaceAll("Up", " \u2191 ");
    raw = raw.replaceAll("Right", " \u2192 ");

    try{
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(log), "UTF-8"));
        bufferedWriter.write(raw + "\n");
        System.out.println(raw + "\n");
        bufferedWriter.close();

    }catch(IOException e) {}
}

Then, you need to make sure that your file viewer is also set to UTF-8. It seems that your file viewer might be viewing the file in ANSI instead. Changing that setting would depend on your file viewer -- try Googling "[your file viewer name] UTF-8".

k_ssb
  • 6,024
  • 23
  • 47