如何在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 婆婆高寿祝福语大全简短