Special characters are displayed in the Java IDE, but not in a program launched from a jar file

I am trying to create a Chinese card program in Java to help me learn Chinese. I use intelliJ IDEA 10. The main process is that my program will read a file saved on the local computer to create cards. The file is written using the File class in java. When opened in a notebook, it displays all the characters properly.

When I run it in the IDE, I can display hieroglyphics as well as pinyin characters (mostly vowels with inscriptions above them). However, when I created the jar file and ran the program from there, it can no longer display special characters and ends up showing a bunch of weird characters.

Any ideas on why this is and how to fix it?

+3
source share
2 answers

IntelliJ does not use the default encoding for the platform; it automatically determines it based on the encoding of the source files. When running code outside of IntelliJ, you need to make sure that you explicitly specify the correct encoding when reading / writing the file. You can do this by specifying it as the 2nd argument of the constructor InputStreamReaderand OutputStreamWriteraccordingly.

File file = new File("/foo.txt");
Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
// ...

Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
// ...

In addition, you also need to ensure that the viewer also supports fonts. The Windows Command Console, for example, does not support Chinese. You will need to create a Swing application to present the results.

+4
source

Perhaps this is an encoding problem?

File . FileOutputStream Writer. , . ( .)

, FileWriter. , , FileWriter , . , , , UTF-8 - .

FileWriter :

Charset utf8 = Charset.forName("UTF-8");
OutputStream os = new FileOutputStream(file);
try {
  Writer wr = new OutputStreamWriter(os, utf8);
  wr.write("whatever strings you want to write");
  wr.close();
} finally {
  os.close();
}
0

All Articles