简体   繁体   中英

Java sending UTF-8 characters after compiled to Jar not working

This is really strange, when i am running my application from within NetBeans everything works fine. However when i build the app into a Jar and run it from the Jar the following code converts characters like ä, ö, å to ?

os = new DataOutputStream(socket.getOutputStream()); 
String string = "{\"id\":1,\"type\":\"" + methoden + "\",\"message\":\"" + msget + "\"}";

PrintWriter pw = new PrintWriter(os);
pw.println(string);
pw.flush(); 

In the above example the String msget = "Hej där, vad händer"

When i console.log this on the server i get: {"id":"1", "type":message, "message": "Hej d?r, vad h?nder "}

Again, this does only happend when i compile my app into a Jar.

Any ideas what is going on?

You get question marks when the text encoding you are using does not support a given character.

PrintWriter pw = new PrintWriter(os);

When you are not setting a specific character set, the behaviour becomes platform-dependent. For example, environment variables will be taken into consideration, which may be different when started from inside Netbeans.

Always specify the character set to use

PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); // or whatever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM