Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

How do I properly set the default character encoding used by the JVM (1.5.x) programmatically?

I have read that -Dfile.encoding=whatever used to be the way to go for older JVMs... I don't have that luxury for reasons I won't get into.

I have tried:

System.setProperty("file.encoding", "UTF-8");

And the property gets set, but it doesn't seem to cause the final getBytes call below to use UTF8:

    System.setProperty("file.encoding", "UTF-8");

    byte inbytes[] = new byte[1024];

    FileInputStream fis = new FileInputStream("response.txt");

    fis.read(inbytes);

    FileOutputStream fos = new FileOutputStream("response-2.txt");

    String in = new String(inbytes, "UTF8");

    fos.write(in.getBytes());

1 Answer

0 votes
by (46k points)

Sadly, the file.encoding property has to be defined as the JVM starts up; by the time your main program is entered, the character encoding practiced by String.getBytes() and the default constructors of InputStreamReader and OutputStreamWriter has been lastingly cached.

 in a particular case like this, the environment variable JAVA_TOOL_OPTIONS can be used to define this property, but it's usually done like this:

java -Dfile.encoding=UTF-8 … com.x.Main

Charset.defaultCharset() will reflect adjustments to the file.encoding property, but most of the code in the focus Java libraries that need to define the default character encoding does not apply this tool.

When you are encoding or decoding, you can question the file.encoding property or Charset.defaultCharset() to detect the current default encoding, and try the relevant method or constructor overload to define it.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...