Java如何读写UTF-8编码数据到文件
在我们的应用程序中,我们经常需要处理UTF-8编码的文件。这可能是由于本地化需求或者简单地处理用户根据某些要求提供的输入。
甚至一些数据源可能只提供UTF-8格式的数据。在这个Java教程中,我们将学习两个非常简单的例子,从文件中读取和写入UTF-8内容。
1.将UTF-8编码的数据写入文件
下面给出了一个Java示例,演示了如何将“UTF-8”编码的数据写入文件。在创建OutputStreamWriter时,它使用了字符编码“UTF-8”。
File file = new File("c:\temp\test.txt"); try (Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file), StandardCharsets.UTF_8))) { out.append("www.frpkj.com") .append("rn") .append("UTF-8 Demo") .append("rn") .append("क्षेत्रफल = लंबाई * चौड़ाई") .append("rn"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); }
在运行Eclipse中的示例之前,我们需要启用Eclipse IDE以支持UTF-8字符集。默认情况下,它是禁用的。
2.从文件中读取UTF-8编码的数据
我们需要将StandardCharsets.UTF_8传递给InputStreamReader构造函数,以从UTF-8编码的文件中读取数据。
File file = new File("c:\temp\test.txt"); try (BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(file), "UTF8"))) { String str; while ((str = in.readLine()) != null) { System.out.println(str); } } catch (Exception e) { System.out.println(e.getMessage()); }
输出:
www.frpkj.com UTF-8 Demo क्षेत्रफल = लंबाई * चौड़ाई