使用 Java 將 UTF8 資料寫入檔案
通常,資料以位的形式(1 或 0)儲存在計算機中。有各種可用的編碼方案,指定每個字元表示的位元組集。
Unicode (UTF) - 代表 Unicode 轉換格式。它由 Unicode Consortium 開發。如果您想建立使用來自多個字元集的字元的文件,則可以使用單個 Unicode 字元編碼來實現。它提供 3 種類型的編碼。
UTF-8 - 它以 8 位單元(位元組)的形式出現,UTF8 中的一個字元可以是 1 到 4 個位元組長,這使得 UTF8 成為可變寬度。
UTF-16 - 它以 16 位單元(短整數)的形式出現,它可以是 1 或 2 個短整數長,這使得 UTF16 成為可變寬度。
UTF-32 - 它以 32 位單元(長整數)的形式出現。它是一種固定寬度格式,長度始終為 1 個“長整數”。
將 UTF 資料寫入檔案
java.io.DataOutputStream 類的 write UTF() 方法接受一個 String 值作為引數,並使用修改後的 UTF-8 編碼將其寫入當前輸出流。因此,要將 UTF-8 資料寫入檔案 -
透過傳遞表示所需檔案路徑的 String 值作為引數來例項化 FileOutputStream 類。
透過將上面建立的 FileOutputStream 物件作為引數來例項化 DataOutputStream 類。
使用 write UTF() 方法將 UTF 資料寫入上面建立的 OutputStream 物件。
使用 flush() 方法將 OutputStream 物件的內容重新整理到檔案(目標)。
示例
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class UTF8Example {
public static void main(String args[]) throws Exception{
//Instantiating the FileOutputStream class
FileOutputStream fileOut = new FileOutputStream("D:\samplefile.txt");
//Instantiating the DataOutputStream class
DataOutputStream outputStream = new DataOutputStream(fileOut);
//Writing UTF data to the output stream
outputStream.writeUTF("టుటోరియల్స్ పాయింట్ కి స్వాగతిం");
outputStream.flush();
System.out.println("Data entered into the file");
}
}輸出
Data entered into the file
java.nio.file.Files 類的 newBufferedWriter() 方法接受一個表示檔案路徑的 Path 類物件和一個表示要讀取的字元序列型別的 Charset 類物件,並返回一個 BufferedWriter 物件,該物件可以以指定的格式寫入資料。
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 類物件。
建立/獲取一個 BufferedWriter 物件,該物件可以寫入 UtF-8 資料,並透過上面建立的 Path 物件和 StandardCharsets.UTF_8 作為引數。
使用 append() 將 UTF-8 資料追加到上面建立的 BufferedWriter 物件。
使用 flush() 方法將 BufferedWriter 的內容重新整理到(目標)檔案。
示例
import java.io.BufferedWriter;
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
Path path = Paths.get("D:\samplefile.txt");
//Creating a BufferedWriter object
BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
//Appending the UTF-8 String to the file
writer.append("టుటోరియల్స్ పాయింట్ కి స్వాగతిం");
//Flushing data to the file
writer.flush();
System.out.println("Data entered into the file");
}
}輸出
Data entered into the file
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP