Is there anyway to update the default charset encoding during runtime in java? thanks,
-
1Did you try to search for it? Duplicate? http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding – Peter Svensson Feb 14 '12 at 19:32
2 Answers
No, there is no practical way to change it. In OpenJDK for instance the default charset is read from the file.encoding
system property pretty much when the virtual machine starts and it gets stored in a private static field in the Charset
class. If you need to use a different encoding you should use the classes that allow specifying the encodings.
You may be able to hack your way in by changing private fields through reflection. This is something you may try if you really, really, have no other option. You are targeting your code to specific versions of specific JVMs, and it'll likely not work on others. This is how you would change the default charset in current versions of OpenJDK:
import java.nio.charset.Charset;
import java.lang.reflect.*;
public class test {
public static void main(String[] args) throws Exception {
System.out.println(Charset.defaultCharset());
magic("latin2");
System.out.println(Charset.defaultCharset());
}
private static void magic(String s) throws Exception {
Class<Charset> c = Charset.class;
Field defaultCharsetField = c.getDeclaredField("defaultCharset");
defaultCharsetField.setAccessible(true);
defaultCharsetField.set(null, Charset.forName(s));
// now open System.out and System.err with the new charset, if needed
}
}

- 108,737
- 14
- 143
- 193
-
2Indeed, only if you **really, really** have no other option. Beware that this depends on implementation details of your specific Java version; this may not work on future Java versions, or Java implementations other than Oracle's. – Jesper Feb 14 '12 at 21:30
-
Good point, I've added wording to make it more clear that this code works on current versions of OpenJDK only. – Joni Feb 14 '12 at 22:25
Solved, relacionations: Today Every time I try to run and build I get the following error message... To Solve accessible: module java.base does not “opens java.io” to unnamed module Error Just downgrade JDK 16 to JDK 15 ...
https://exerror.com/accessible-module-java-base-does-not-opens-java-io-to-unnamed-module/

- 49
- 2