文章目录
经典参考文章
Charset.defaultCharset()和file.encoding的关系
一切存储在硬盘上的数据都是二进制数据,而IO流从硬盘读取到内存中的数据都存储在byte数组中,byte字节数组需要按照对应的编码规则才能解码为正确的字符串、图片等对象。
Charset的defaultCharset方法实现
从Charset的defaultCharset方法源码我们可以看到,默认字符集是最终通过System.getProperty(“file.encoding”)方法来获取的。
- 当JVM启动时,通过JVM参数-Dfile.encoding=XXX指定了编码格式,以此编码格式为准。但如果XXX是不支持的字符集,则默认使用UTF-8编码
- 当JVM启动时,没有指定JVM参数-Dfile.encoding,则以JVM所在操作系统的默认字符集为准。
注意:在Windows的DOS窗口输入:chcp,显示983,则表示是GBK
public static Charset defaultCharset() {
if (defaultCharset == null) {
synchronized (Charset.class) {
String csn = AccessController.doPrivileged(
new GetPropertyAction("file.encoding"));
Charset cs = lookup(csn);
if (cs != null)
defaultCharset = cs;
else
defaultCharset = forName("UTF-8");
}
}
return defaultCharset;
}
public String run() {
String var1 = System.getProperty(this.theProp);
return var1 == null ? this.defaultVal : var1;
}
如何将byte数组通过指定编码方式转换为字符串
String的getBytes()方法和String(byte bytes[])构造方法默认使用Charset.defaultCharset()来获取编码字符集,当然我们也可以手动指定编码方式
byte[] b = "中国".getBytes();
System.out.println(new String(b, "GBK"));//涓浗
System.out.println(new String(b, StandardCharsets.UTF_8)); //中国
byte[] b1 = "中国".getBytes("GBK");
System.out.println(new String(b1, "GBK"));//中国
System.out.println(new String(b1, StandardCharsets.UTF_8)); //�й�
class String{
public String(byte bytes[], int offset, int length) {
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(bytes, offset, length);
}
}
# StringCoding.decode方法的定义
static char[] decode(byte[] ba, int off, int len) {
String csn = Charset.defaultCharset().name();
try {
// use charset name decode() variant which provides caching.
return decode(csn, ba, off, len);
} catch (UnsupportedEncodingException x) {
warnUnsupportedCharset(csn);
}
转换流InputStreamReader和OutStreamWriter使用了Charset.defaultCharset()方法
InputStreamReader 将字节输入流转换为字符流,而OutStreamWriter将字符流转换为字节输出流
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("C:\\Users\\admin\\Desktop\\test.txt");
InputStreamReader isr = new InputStreamReader(fis);
//InputStreamReader isr2 = new InputStreamReader(fis, StandardCharsets.UTF_8);
FileOutputStream fos = new FileOutputStream("C:\\Users\\admin\\Desktop\\1.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
//OutputStreamWriter osw2 = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
char[] chars = new char[1];
int len;
while ((len = isr.read(chars))!= -1) {
osw.write(chars, 0, len);
osw.flush();
}
isr.close();
osw.close();
}