使用Java从文件读取UTF8数据

通常,数据以位(1或0)的形式存储在计算机中。有多种可用的编码方案来指定每个字符代表的字节集。

Unicode(UTF) -代表Unicode转换格式。它是由Unicode联盟开发的。如果要创建使用来自多个字符集的字符的文档,则可以使用单个Unicode字符编码来创建。它提供3种类型的编码。

  • UTF-8-它以8位为单位(字节),UTF8中的字符长度可以从1到4个字节,从而使UTF8的宽度可变。

  • UTF-16-它以16位为单位(短字节),长度可以是1或2个短字节,从而使UTF16的宽度可变。

  • UTF-32-它以32位单元(长)为单位。它是一种固定宽度的格式,长度始终为1“长”。

将UTF数据写入文件

java.io.DataOutputStreamreadUTF()方法将经过修改的UTF-8编码的数据读取到String中并返回。因此要读取UTF-8数据到文件-

  • 通过传递表示所需文件路径的String值作为参数来实例化FileInputStream类。

  • 实例化DataInputStream类,绕过上面创建的FileInputStream对象作为参数。

  • 使用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 {
         //实例化FileInputStream类
         FileInputStream fileIn = new FileInputStream("D:\\test.txt");
         //实例化DataInputStream类
         DataInputStream inputStream = new DataInputStream(fileIn);
         //从DataInputStream读取UTF数据
         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());
   }
}

输出结果

文件的内容: ยินดีต้อนรับสู่เครือข่ายการสอนขั้นพื้นฐาน

java.nio.file.Files类的新bufferedReader()方法接受Path类的对象,该对象表示文件的路径,Charset类的对象表示要读取的字符序列的类型。并且,返回一个BufferedReader对象,该对象可以读取指定格式的数据。

字符集的值可以是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类的对象。

  • 创建/获取一个BufferedReader对象,该对象可以读取UtF-8数据,而绕过上面创建的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);
      //创建BufferedReader对象
      BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
      //从文件中读取UTF-8数据
      StringBuffer buffer = new StringBuffer();
      int ch = 0;
      while((ch = reader.read())!=-1) {
         buffer.append((char)ch+reader.readLine());
      }
      System.out.println("文件的内容: "+buffer.toString());
   }
}

输出结果

文件的内容: ยินดีต้อนรับสู่เครือข่ายการสอนขั้นพื้นฐาน