Setting the default Java character encoding

后端 未结 17 1722
终归单人心
终归单人心 2020-11-21 06:09

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

17条回答
  •  盖世英雄少女心
    2020-11-21 06:50

    Not clear on what you do and don't have control over at this point. If you can interpose a different OutputStream class on the destination file, you could use a subtype of OutputStream which converts Strings to bytes under a charset you define, say UTF-8 by default. If modified UTF-8 is suffcient for your needs, you can use DataOutputStream.writeUTF(String):

    byte inbytes[] = new byte[1024];
    FileInputStream fis = new FileInputStream("response.txt");
    fis.read(inbytes);
    String in = new String(inbytes, "UTF8");
    DataOutputStream out = new DataOutputStream(new FileOutputStream("response-2.txt"));
    out.writeUTF(in); // no getBytes() here
    

    If this approach is not feasible, it may help if you clarify here exactly what you can and can't control in terms of data flow and execution environment (though I know that's sometimes easier said than determined). Good luck.

提交回复
热议问题