我正在创建 ASCII 字符集格式的文本文件。再次阅读时,它
给出 UTF8 字符集。为什么它给出 UTF8 字符集而不是 ASCII?
public static void fileStreamWriter() throws IOException {
Charset cs = Charset.forName("US-ASCII");
System.setProperty("file.encoding", "US-ASCII");
String text = "ABCDEFGHIJKLMNOP";
String stCr = new String(text.getBytes());
Writer writer = new OutputStreamWriter(new
FileOutputStream("C:/upload/FItest"), cs);
try {
writer.write(stCr);
writer.flush();
} finally {
writer.close();
}
}
public static void readEncodingCharset(String path) throws IOException
{
System.setProperty("file.encoding", "US-ASCII");
FileInputStream fis = null;
InputStreamReader isr = null;
String s;
try {
fis = new FileInputStream("C:/upload/FItest");
isr = new InputStreamReader(fis);
s = isr.getEncoding();
System.out.println("Charset Encoding type : "+s);
} catch (Exception e) {
e.printStackTrace();
} finally {
fis.close();
isr.close();
}
}
最佳答案
删除 System.setProperty
行,它们没有用,不会按照您的想法行事。
由于您没有在 InputStreamReader
构造函数中指定编码,因此使用平台默认值,在您的情况下似乎是 UTF-8
。将 "US-ASCII"
作为参数添加到 InputStreamReader
。
InputStreamReader
不会 猜测编码。除非您指定不同,否则它使用平台默认值,并且您应该始终明确指定编码以确保该程序在不同平台上工作相同。
关于java - 在java中获取UTF8字符集而不是ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32523466/