Home >Java >javaTutorial >How to Write UTF-8 Files in Java?

How to Write UTF-8 Files in Java?

DDD
DDDOriginal
2024-12-01 17:38:13525browse

How to Write UTF-8 Files in Java?

Writing UTF-8 Files in Java

Question:

How to write UTF-8 files in Java?

Background:

The existing code uses FileWriter to create 1252 code page files, which need to be forced to UTF-8 files.

Solution:

Unable to specify encoding when using FileWriter. To create a UTF-8 file, use the following steps:

  1. Create a FileOutputStream object.
  2. Wrap the FileOutputStream object in an OutputStreamWriter object, specifying the encoding (StandardCharsets.UTF_8) in the constructor.
  3. Use try-with-resources statement to write data to OutputStreamWriter.

The following example demonstrates how to do this:

try (OutputStreamWriter writer =
             new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8)) {
    // 写入数据
}

The above is the detailed content of How to Write UTF-8 Files in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn