ChatGPT解决这个技术问题 Extra ChatGPT

如何用 Java 编写 UTF-8 文件?

我有一些当前代码,问题是它创建了一个 1252 代码页文件,我想强制它创建一个 UTF-8 文件

任何人都可以帮我处理这段代码,正如我所说的那样,它目前可以工作......但我需要强制保存 utf .. 我可以传递一个参数或其他什么吗?

这就是我所拥有的,任何帮助都非常感谢

var out = new java.io.FileWriter( new java.io.File( path )),
        text = new java.lang.String( src || "" );
    out.write( text, 0, text.length() );
    out.flush();
    out.close();
如果可能,请发布通过编译器的代码。
它似乎是犀牛(javascript)

N
Neuron

不使用 FileWriter,而是创建一个 FileOutputStream。然后,您可以将其包装在 OutputStreamWriter 中,这允许您在构造函数中传递编码。然后您可以将数据写入 try-with-resources Statement 中:

try (OutputStreamWriter writer =
             new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
    // do stuff
}

...并诅咒 Sun 没有将构造函数放入采用 Charset 的 FileWriter 中。
这似乎是一个奇怪的疏忽。他们仍然没有修复它。
@Jon Skeet:鉴于 FileWriter 是 FileOutputStream 的包装器,它假定默认编码和缓冲区大小,这难道不是重点吗?
抱歉,我的意思是 OutputStreamWriter,而不是 FileOutputStream。
我建议将实现 Closeable 接口的类型的每个声明分开,特别是如果您将 try 与资源一起使用,例如“new FileOutputStream”;是一种很好的做法,可以避免将来出现诸如“IOException:打开的文件过多”之类的错误。
n
nhahtdh

尝试这个

Writer out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("outfilename"), "UTF-8"));
try {
    out.write(aString);
} finally {
    out.close();
}

我认为有一个错字。 Writer out = ... 应更正为 BufferedWriter out = ...
Writer 是抽象类,BufferedWriter 正在实现,并声明了 write() + close()。
这将创建一个没有 BOM 的实际 UTF-8,而不仅仅是 UTF-8。有办法强制吗?
N
Neuron

尝试使用 Apache Commons 中的 FileUtils.write

您应该能够执行以下操作:

File f = new File("output.txt"); 
FileUtils.writeStringToFile(f, document.outerHtml(), "UTF-8");

如果文件不存在,这将创建该文件。


这也会产生一个没有 BOM 的 UTF-8 文件……我不知道它是否相关。
@Smarty 仅当您已经在使用 Apache Commons 时。否则,仅仅因为你不想再写几个字符就包含另一个 jar 似乎是一种可怕的浪费。
我在 FileUtils 类中看不到“write(..)”方法。我检查了公共 IO 1.4
如果您阅读问题中显示的链接上的 Java 文档,那么它会告诉您引入写入 API 的 Commons IO API 版本。看起来写 API 是从 v2.0 开始引入的。
只想提一下,我使用了 FileUtils.writeStringToFile(...) 方法(使用 commons-io-1.3.1.jar)而不是 FileUtils.write(...)。
N
Neuron

从 Java 7 开始,您可以更简洁地使用 Files.newBufferedWriter 执行相同的操作:

Path logFile = Paths.get("/tmp/example.txt");
try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {
    writer.write("Hello World!");
    // ...
}

E
Emperorlou

这里给出的所有答案都不起作用,因为 java 的 UTF-8 写作有问题。

http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html


据我所知,这个错误是这个(因为那篇文章的作者没有提及它):bugs.sun.com/view_bug.do?bug_id=4508058
写入时唯一的问题是缺少 BOM。没什么大不了。另一方面,读取带有 BOM 的文件需要手动剥离它。
UTF-8 不需要 BOM,因此从技术上讲,写入的文件仍然是有效的 UTF-8 编码文本文件。错误在于使用 BOM 读取 UTF-8。
@Chris bugs.sun.com 链接已损坏。你有一个有效的吗?
仍然对我有用;我没有登录或任何东西。尝试在谷歌上搜索错误 4508058。
b
boxofrats
var out = new java.io.PrintWriter(new java.io.File(path), "UTF-8");
text = new java.lang.String( src || "" );
out.print(text);
out.flush();
out.close();

M
McDowell

Java 7 Files utility type 对于处理文件很有用:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;

public class WriteReadUtf8 {
  public static void main(String[] args) throws IOException {
    List<String> lines = Arrays.asList("These", "are", "lines");

    Path textFile = Paths.get("foo.txt");
    Files.write(textFile, lines, StandardCharsets.UTF_8);

    List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);

    System.out.println(lines.equals(read));
  }
}

Java 8 version 允许您省略 Charset 参数 - 这些方法默认为 UTF-8。


D
Dharmesh Patel

我们可以用 java 编写 UTF-8 编码的文件,使用 PrintWriter 编写 UTF-8 编码的 xml

或点击here

PrintWriter out1 = new PrintWriter(new File("C:\\abc.xml"), "UTF-8");

A
Ammad

下面的示例代码可以逐行读取文件并以 UTF-8 格式写入新文件。另外,我明确指定了 Cp1252 编码。

    public static void main(String args[]) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(
            new FileInputStream("c:\\filenonUTF.txt"),
            "Cp1252"));
    String line;

    Writer out = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(
                    "c:\\fileUTF.txt"), "UTF-8"));

    try {

        while ((line = br.readLine()) != null) {

            out.write(line);
            out.write("\n");

        }

    } finally {

        br.close();
        out.close();

    }
}