Java – 读写 UTF-8 编码数据

Java – 读写 UTF-8 编码数据

原文: https://howtodoinjava.com/java/io/how-to-read-write-utf-8-encoded-data-in-java/

很多时候,我们需要在应用程序中处理 UTF-8 编码的数据。 这可能是由于本地化需求或仅仅是出于某些要求而处理用户输入。 甚至数据源也只能以这种格式提供数据。 在本教程中,我将提供两个非常简单的读取和写入操作示例。

如何写入 UTF-8 编码数据

这是演示如何从 Java 文件中写入“ UTF-8”编码数据的示例

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class WriteUTF8Data
{
   public static void main(String[] args)
   {
      try
      {
         File fileDir = new File("c:\\temp\\test.txt");
         Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir), "UTF8"));
         out.append("Howtodoinjava.com").append("\r\n");
         out.append("UTF-8 Demo").append("\r\n");
         out.append("क्षेत्रफल = लंबाई * चौड़ाई").append("\r\n");
         out.flush();
         out.close();
      } catch (UnsupportedEncodingException e)
      {
         System.out.println(e.getMessage());
      } catch (IOException e)
      {
         System.out.println(e.getMessage());
      } catch (Exception e)
      {
         System.out.println(e.getMessage());
      }
   }
}

您可能希望启用 Eclipse IDE 以支持 UTF-8 字符集。 默认情况下,它是禁用的。 如果您希望在 eclipse 中启用 UTF-8 支持,您将获得我以前的文章的必要帮助:

如何编译和运行以另一种语言编写的 Java 程序

如何读取 UTF-8 编码数据

这是演示如何从 Java 文件中读取“ UTF-8”编码数据的示例

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class ReadUTF8Data
{
   public static void main(String[] args)
   {
      try {
         File fileDir = new File("c:\\temp\\test.txt");

         BufferedReader in = new BufferedReader(
            new InputStreamReader(
                       new FileInputStream(fileDir), "UTF8"));

         String str;

         while ((str = in.readLine()) != null) {
             System.out.println(str);
         }

                 in.close();
         } 
         catch (UnsupportedEncodingException e) 
         {
             System.out.println(e.getMessage());
         } 
         catch (IOException e) 
         {
             System.out.println(e.getMessage());
         }
         catch (Exception e)
         {
             System.out.println(e.getMessage());
         }
   }
}

Output:

Howtodoinjava.com
UTF-8 Demo
क्षेत्रफल = लंबाई * चौड़ाई

祝您学习愉快!