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

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

如何写入 UTF-8 编码数据

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

  1. import java.io.BufferedWriter;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.OutputStreamWriter;
  6. import java.io.UnsupportedEncodingException;
  7. import java.io.Writer;
  8. public class WriteUTF8Data
  9. {
  10. public static void main(String[] args)
  11. {
  12. try
  13. {
  14. File fileDir = new File("c:\\temp\\test.txt");
  15. Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir), "UTF8"));
  16. out.append("Howtodoinjava.com").append("\r\n");
  17. out.append("UTF-8 Demo").append("\r\n");
  18. out.append("क्षेत्रफल = लंबाई * चौड़ाई").append("\r\n");
  19. out.flush();
  20. out.close();
  21. } catch (UnsupportedEncodingException e)
  22. {
  23. System.out.println(e.getMessage());
  24. } catch (IOException e)
  25. {
  26. System.out.println(e.getMessage());
  27. } catch (Exception e)
  28. {
  29. System.out.println(e.getMessage());
  30. }
  31. }
  32. }

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

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

如何读取 UTF-8 编码数据

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

  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.UnsupportedEncodingException;
  7. public class ReadUTF8Data
  8. {
  9. public static void main(String[] args)
  10. {
  11. try {
  12. File fileDir = new File("c:\\temp\\test.txt");
  13. BufferedReader in = new BufferedReader(
  14. new InputStreamReader(
  15. new FileInputStream(fileDir), "UTF8"));
  16. String str;
  17. while ((str = in.readLine()) != null) {
  18. System.out.println(str);
  19. }
  20. in.close();
  21. }
  22. catch (UnsupportedEncodingException e)
  23. {
  24. System.out.println(e.getMessage());
  25. }
  26. catch (IOException e)
  27. {
  28. System.out.println(e.getMessage());
  29. }
  30. catch (Exception e)
  31. {
  32. System.out.println(e.getMessage());
  33. }
  34. }
  35. }
  36. Output:
  37. Howtodoinjava.com
  38. UTF-8 Demo
  39. क्षेत्रफल = लंबाई * चौड़ाई

祝您学习愉快!