使用Java讀取檔案中的UTF8資料
一般來說,資料以位元(1 或 0)的形式儲存在計算機中。有多種編碼方案可用於指定每個字元所表示的位元組集。
Unicode (UTF) - 代表 Unicode 轉換格式。它由 Unicode Consortium 開發。如果您想建立使用來自多個字元集的字元的文件,則可以使用單個 Unicode 字元編碼來實現。它提供三種編碼型別。
UTF-8 - 它以 8 位單元(位元組)為單位,UTF8 中的一個字元可以是 1 到 4 個位元組長,這使得 UTF8 成為可變寬度。
UTF-16 - 它以 16 位單元(短整數)為單位,它可以是 1 或 2 個短整數長,這使得 UTF16 成為可變寬度。
UTF-32 - 它以 32 位單元(長整數)為單位。它是一種固定寬度格式,長度始終為 1 個“長整數”。
將 UTF 資料寫入檔案
java.io.DataOutputStream 的 readUTF() 方法將以修改後的 UTF-8 編碼的資料讀取到字串中並返回它。因此,要將 UTF-8 資料讀取到檔案中:
透過傳遞表示所需檔案路徑的字串值作為引數來例項化 *FileInputStream* 類。
透過將上面建立的 *FileInputStream* 物件作為引數來例項化 DataInputStream 類。
使用 *readUTF()* 方法從 InputStream 物件讀取 UTF 資料。
示例
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class UTF8Example {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer();
try {
//Instantiating the FileInputStream class
FileInputStream fileIn = new FileInputStream("D:\test.txt");
//Instantiating the DataInputStream class
DataInputStream inputStream = new DataInputStream(fileIn);
//Reading UTF data from the DataInputStream
while(inputStream.available()>0) {
buffer.append(inputStream.readUTF());
}
}
catch(EOFException ex) {
System.out.println(ex.toString());
}
catch(IOException ex) {
System.out.println(ex.toString());
}
System.out.println("Contents of the file: "+buffer.toString());
}
}輸出
Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం
java.nio.file.Files 類的新的 bufferedReader() 方法接受表示檔案路徑的 **Path** 類的物件和表示要讀取的字元序列型別的 **Charset** 類的物件,並返回一個可以讀取指定格式資料的 BufferedReader 物件。
Charset 的值可以是 StandardCharsets.UTF_8 或 StandardCharsets.UTF_16LE 或 StandardCharsets.UTF_16BE 或 StandardCharsets.UTF_16 或 StandardCharsets.US_ASCII 或 StandardCharsets.ISO_8859_1
因此,要將 UTF-8 資料讀取到檔案中:
使用 **java.nio.file.Paths** 類的 **get()** 方法建立/獲取表示所需路徑的 Path 類物件。
建立/獲取一個可以讀取 UTF-8 資料的 BufferedReader 物件,透過將上面建立的 Path 物件和 *StandardCharsets.UTF_8* 作為引數。
使用 BufferedReader 物件的 readLine() 方法讀取檔案的內容。
示例
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class UTF8Example {
public static void main(String args[]) throws Exception{
//Getting the Path object
String filePath = "D:\samplefile.txt";
Path path = Paths.get(filePath);
//Creating a BufferedReader object
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
//Reading the UTF-8 data from the file
StringBuffer buffer = new StringBuffer();
int ch = 0;
while((ch = reader.read())!=-1) {
buffer.append((char)ch+reader.readLine());
}
System.out.println("Contents of the file: "+buffer.toString());
}
}輸出
Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP