Mittwoch, 21. Oktober 2015

set file.encoding in a JVM

To set the default file.encoding in a JVM you could set it in the JVM startup as -Dfile.encoding=UTF-8 or in JAVA_TOOLS_OPTIONS with the same part. But if you want to set it programmatically after the JVM already started?
A System.setProperty("file.encoding", "UTF-16"); will only set the file.encoding property. All other classes which rely on the defaultCharset, like all Streams and Buffers won't recognize that change. Here is a Junit Test, which shows you how to reset the Charset.defaultCharset field:


package de.kambrium;

import java.lang.reflect.Field;
import java.nio.charset.Charset;

import org.junit.Before;
import org.junit.Test;

public class CharsetTest {

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        dump("Actual system config");
        System.setProperty("file.encoding", "UTF-16");
        dump("Config after System.setProperty(\"file.encoding\", \"UTF-16\")");
        Field cs = Charset.class.getDeclaredField("defaultCharset");
        cs.setAccessible(true);
        cs.set(null, null);
        dump("Config after manipulating defatulCharset field");
    }

    private void dump(String msg) {
        System.out.println(msg);
        System.out.println("****************************************************************");
        System.out.println("file.encoding          = " + System.getProperty("file.encoding"));
        System.out.println("defaultCharset         = " + Charset.defaultCharset());
        System.out.println("****************************************************************");
        System.out.println("");
    }
}


Output will look like this

Actual system config
****************************************************************
file.encoding          = UTF-8
defaultCharset         = UTF-8
****************************************************************

Config after System.setProperty("file.encoding", "UTF-16")
****************************************************************
file.encoding          = UTF-16
defaultCharset         = UTF-8
****************************************************************

Config after manipulating defatulCharset field
****************************************************************
file.encoding          = UTF-16
defaultCharset         = UTF-16
****************************************************************

Keine Kommentare:

Kommentar veröffentlichen