如何在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 送给学长毕业祝福语简短