如何將字串從 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());
//get the UTF-8 data Reader
reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
//convert UTF-8 to Unicode
int data = reader.read();
while(data != -1){
char theChar = (char) data;
System.out.print(theChar);
data = reader.read();
} reader.close();
System.out.println();
//Convert Unicode to UTF-8 Bytes
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP