如何在java中将ANSI转换为utf8?

PS *_*mar 7 java unicode

我有一个文本文件,它是ANSI编码,我必须将其转换为UTF8编码.

我的文本文件是这样的 Stochastic programming is an area of mathematical programming that studies how to model decision problems under uncertainty. For example, although a decision might be necessary at a given point in time, essential information might not be available until a later time.

sgb*_*gbj 7

你可以使用java.nio.charset.Charset类显式(windows-1252是ANSI的正确名称):

public static void main(String[] args) throws IOException {
    Path p = Paths.get("file.txt");
    ByteBuffer bb = ByteBuffer.wrap(Files.readAllBytes(p));
    CharBuffer cb = Charset.forName("windows-1252").decode(bb);
    bb = Charset.forName("UTF-8").encode(cb);
    Files.write(p, bb.array());
}
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以在一行中输入=)

Files.write(Paths.get("file.txt"), Charset.forName("UTF-8").encode(Charset.forName("windows-1252").decode(ByteBuffer.wrap(Files.readAllBytes(Paths.get("file.txt"))))).array());
Run Code Online (Sandbox Code Playgroud)


Lak*_*ake 0

ASCII 字符子集映射到 UTF8 中的相同字符编码,因此文件实际上不需要任何转换。

要以 UTF-8 输出文件,您可以使用:

PrintWriter out = new PrintWriter(new File(filename), "UTF-8");
out.print(text);
out.close();
Run Code Online (Sandbox Code Playgroud)