我有一个文本文件,它是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.
你可以使用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());
}
如果您愿意,可以在一行中输入=)
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());
ASCII 字符子集映射到 UTF8 中的相同字符编码,因此文件实际上不需要任何转换。
要以 UTF-8 输出文件,您可以使用:
PrintWriter out = new PrintWriter(new File(filename), "UTF-8");
out.print(text);
out.close();
| 归档时间: | 
 | 
| 查看次数: | 28020 次 | 
| 最近记录: |