Daniel
Daniel

Reputation: 318

Java text encoding

I read lines from a .txt file into a String list. I show the text in a JTextPane. The encoding is fine when running from Eclipse or NetBeans, however if I create a jar, the encoding is not correct. The encoding of the file is UTF-8. Is there a way to solve this problem?

Upvotes: 0

Views: 229

Answers (2)

Mike Samuel
Mike Samuel

Reputation: 120566

Your problem is probably that you're opening a reader using the platform encoding.

You should manually specify the encoding whenever you convert between bytes and characters. If you know that the appropriate encoding is UTF-8 you can open a file thus:

FileInputStream inputFile = new FileInputStream(myFile);
try {
  FileReader reader = new FileReader(inputFile, "UTF-8");
  // Maybe buffer reader and do something with it.
} finally {
  inputFile.close();
}

Libraries like Guava can make this whole process easier..

Upvotes: 1

Kostas Kryptos
Kostas Kryptos

Reputation: 4111

Have you tried to run your jar as

java -Dfile.encoding=utf-8 -jar xxx.jar

Upvotes: 0

Related Questions