如何在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 岁月祝福语简短10字
13 除夕祝福语简短创意牛年
14 周岁生日祝福语简短唯美
15 幼儿转园祝福语简短
16 艺校元旦祝福语大全简短
17 疫情对妈妈祝福语简短
18 送给平辈生日祝福语简短