1 需求
美国 ASCII
欧洲 扩展ASCII
中国 GB2312 GBK GB18030
全球 Unicode(UCS-2 UCS-4 UTF-8)
2 接口
3 示例代码
示例代码
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
// IDEA 默认字符串编码格式
System.out.println(System.getProperty("file.encoding"));
/**
* GBK UTF-8 中文编码 示例
*/
// 您 使用GBK编码时,占用2个字节
System.out.println("*** *** 您 GBK 编码示例,占用2个字节 *** ***");
byte[] bytes1 = "您".getBytes();
for (byte b1 : bytes1) {
System.out.println(b1);
}
// 您 使用UTF-8编码时,占用3个字节
System.out.println("*** *** 您 UTF-8 编码示例,占用3个字节 *** ***");
byte[] bytes2 = "您".getBytes("UTF-8");
for (byte b2 : bytes2) {
System.out.println(b2);
}
// Windows的cmd命令行默认编码格式
System.out.println("*** *** Windows的cmd命令行默认编码格式 *** ***");
InputStreamReader reader = new InputStreamReader(Runtime.getRuntime().exec("cmd /c dir").getInputStream());
System.out.println(reader.getEncoding());
}
}
示例代码
public class CharsetDemo {
public static void main(String[] args) {
// char转int、char转String
System.out.println("\\r的ascii值:" + Integer.valueOf('\r'));
System.out.println("\\n的ascii值:" + Integer.valueOf('\n'));
System.out.println("CR = '\\r' = 0X0D");
System.out.println("LF = '\\n' = 0X0A");
}
}
4 参考资料
视频
非常详细的字符编码讲解,ASCII、GB2312、GBK、Unicode、UTF-8等知识点都有
文字
Java之字符串的编码方式_想去22世纪的博客-CSDN博客_java 字符串编码
java 怎么判断文本内容的编码格式_IRhythm的博客-CSDN博客_java判断文本编码
Java字符集Charset_a digger的博客-CSDN博客_java 设置charset