/** * @author wx * 测试输出流输出的文件类型 */ public class IOtest { private BufferedOutputStream os1; private OutputStreamWriter os2; /** * @param fileName * 输出文件(字节流) */ private void outputFile1(String fileName){ File f = new File(fileName); try { os1 = new BufferedOutputStream(new FileOutputStream(f)); os1.write("测试".getBytes("")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { os1.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * @param fileName * 输出文件(字符流) */ private void outputFile2(String fileName){ File f = new File(fileName); try { os2 = new OutputStreamWriter(new FileOutputStream(f),"Unicode"); os2.write("测试"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { os2.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { new IOtest().outputFile1("f:/workspace/test1.txt"); new IOtest().outputFile2("f:/workspace/test2.txt"); } }
需要test1.TXT的编码方式为Unicode,此种方式为Unicode big endian。
[code="java"]
os1 = new BufferedOutputStream(new FileOutputStream(f));
byte[] bom={-1, -2};
os1.write(bom);
os1.write("测试".getBytes("UTF-16LE"));
[/code]
JAVA内部使用的unicode是UTF-16BE的,当上面的getBytes中的字符集指定为:
UTF-16或unicode时,文件输出为UTF-16BE,而且本件内包含两个字节的BOM(Byte Order Marker)信息。
UTF-16BE或UTF-16LE时,文件输出为分别为UTF-16BE和UTF-16LE,但文件内不包含BOM信息。
当NODEPAD(记事本)打开文件时会自己判断BOM信息,来以合适的方式打开文件,其中它里面的unicode就是UTF-16LE,unicode big endian就是UTF-16BE。
所以,为了记事本显示为unicode,需要人为的加入BOM信息,如上面的:
[code="java"]
byte[] bom={-1, -2};
os1.write(bom);
[/code]
你的问题是什么?
Unicode编码就是这样啊,包括:UTF-16 LE 和 UTF-16 BE