使用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