John Kramer
John Kramer

Reputation: 11

Update default charset encoding during runtime in java?

Is there anyway to update the default charset encoding during runtime in java? thanks,

Upvotes: 0

Views: 3547

Answers (2)

Heverton Silva Cruz
Heverton Silva Cruz

Reputation: 47

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/

Upvotes: 0

Joni
Joni

Reputation: 111349

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
    }
}

Upvotes: 6

Related Questions