String a = "你好";
File f = null;
f = new File("Out.txt");
if (f.exists()) {
f.delete();
}
FileOutputStream fout = new FileOutputStream(f);
fout.write(a.getBytes(这里指定字符集));
fout.close();
File f = null;
f = new File("Out.txt");
if (f.exists()) {
f.delete();
}
FileOutputStream fout = new FileOutputStream(f);
fout.write(a.getBytes(这里指定字符集));
fout.close();
"GBK"为你制定的字符集
int len = instr.length();
byte[] abyte = new byte[len << 2];
int j = 0;
for (int i = 0; i < len; i++) {
char c = instr.charAt(i); if (c < 0x80) {
abyte[j++] = (byte) c;
}
else if (c < 0x0800) {
abyte[j++] = (byte) ( ( (c >> 6) & 0x1F) | 0xC0);
abyte[j++] = (byte) ( (c & 0x3F) | 0x80);
}
else if (c < 0x010000) {
abyte[j++] = (byte) ( ( (c >> 12) & 0x0F) | 0xE0);
abyte[j++] = (byte) ( ( (c >> 6) & 0x3F) | 0x80);
abyte[j++] = (byte) ( (c & 0x3F) | 0x80);
}
else if (c < 0x200000) {
abyte[j++] = (byte) ( ( (c >> 18) & 0x07) | 0xF8);
abyte[j++] = (byte) ( ( (c >> 12) & 0x3F) | 0x80);
abyte[j++] = (byte) ( ( (c >> 6) & 0x3F) | 0x80);
abyte[j++] = (byte) ( (c & 0x3F) | 0x80);
}
} byte[] retbyte = new byte[j];
for (int i = 0; i < j; i++) {
retbyte[i] = abyte[i];
}
return retbyte;
}
<?xml version="1.0" encoding="GBK"?>
可以避免乱码!
若是写入文本,最简单有效的方法是:
System.setProperty("file.encoding","GBK")
new PrintStream(OutputStream out, boolean autoFlush, String encoding);
encode 可以指定你想用的编码格式。
最简单的就是避免使用io直接输出xml而是使用sax,dom:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty( "encoding", "UTF-8" );