如何在UTF8字节数组之间来回转换字符串
以下示例将展示使用Reader和Writer类将Unicode字符串转换为UTF8字节[],并将UTF8字节[]转换为Unicode字节[]。
示例
IOTester.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.ParseException;
public class I18NTester {
public static void main(String[] args) throws ParseException, IOException {
String input = "This is a sample text" ;
InputStream inputStream = new ByteArrayInputStream(input.getBytes());
//获取UTF-8数据读取器
reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
//将UTF-8转换为Unicode-
int data = reader.read();
while(data != -1){
char theChar = (char) data;
System.out.print(theChar);
data = reader.read();
} reader.close();
System.out.println();
//将Unicode转换为UTF-8字节
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));
writer.write(input); writer.close();
String out = new String(outputStream.toByteArray());
System.out.println(out); }
}输出结果
It will print the following result. This is a sample text This is a sample text
热门推荐
10 八一幼儿祝福语大全简短
11 入学祝福语简短走心
12 婆婆生日祝福语简短的
13 车行销售祝福语简短
14 圣诞饭店祝福语大全简短
15 老人掉牙祝福语简短语
16 生日贺卡祝福语 简短独特
17 送去考试祝福语大全简短
18 法考面试祝福语简短