首页 > 文章列表 > java处理字符的函数

java处理字符的函数

java 函数
313 2022-08-06

1、getBytes是java字符串处理的标准函数,其作用是按照charset编码字符串所表示的字符,并以字节形式表示。

注:字符串在java内存中总是按unicode编码存储。

2、newString根据charset编码对字节数组进行组合识别,转换为unicode存储。

3、setCharacterEncoding()

该函数用于设置http请求或相应的编码。

实例

package com.test.bs;
 
import java.io.UnsupportedEncodingException;
 
public class UnicodeTest2 {
 
public static void main(String[] args) {
String a = "哈哈";
try {
byte[] gb2312 = a.getBytes("GB2312");
byte[] utf = a.getBytes("UTF-8");
for (int i = 0; i < gb2312.length; i++) {
System.out.print(gb2312[i]);
}
System.out.println();
 
for (int i = 0; i < utf.length; i++) {
System.out.print(utf[i]);
}
System.out.println();
 
System.out.println(new String(gb2312));
System.out.println(new String(utf));
System.out.println(System.getProperty("file.encoding"));//当前文件的编码方式
System.out.println(new String(utf, "UTF-8"));
System.out.println(new String(gb2312, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
 
}
}

推荐操作环境:windows7系统、java10版,DELL G3电脑。