【问题标题】:how to convert ANSI to utf8 in java? [duplicate]如何在java中将ANSI转换为utf8? [复制]
【发布时间】:2013-08-09 06:28:29
【问题描述】:

我有一个文本文件,它是 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.

【问题讨论】:

  • ANSI encoding is a slightly generic term used to refer to the standard code page on a system。换句话说,这取决于您正在运行的系统的语言环境。如果您的意思是 ASCII,则文本已经是两者,因为标准 ASCII 字符 (

标签: java unicode


【解决方案1】:

您可以明确地使用 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());

【讨论】:

    【解决方案2】:

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

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

    PrintWriter out = new PrintWriter(new File(filename), "UTF-8");
    out.print(text);
    out.close();
    

    【讨论】:

    • 我试试这个,但它不能从 ASCII 转换为 UTF-8
    • 我的意思是,应该没有什么可以转换的,真的。 ASCII 文件已经是 UTF-8 兼容的。
    • 对不起,我的意思是 ANSI 到 UTF8
    • @Lake 很抱歉,但是对于重音字符,可能需要进行转换。
    【解决方案3】:

    你可以试试这个

    InputStream inputStream = new BufferedInputStream(new FileInputStream("D:\\sample.txt"));
        Reader reader =
                new InputStreamReader(inputStream, Charset.forName("UTF-8"));
    

    【讨论】:

      【解决方案4】:

      我不是专家,但在这里找到了一个可以帮助您的链接:Converting a txt File from ANSI to UTF-8 programmatically

      这里解释了一些与此相关的问题:http://www.drillio.com/en/software-development/java/encoded-string-too-long-64kb-limit/

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2011-05-22
        • 2011-04-16
        • 1970-01-01
        • 2016-02-10
        • 2013-12-15
        • 2015-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多