简体   繁体   English

将Java文件保存为UTF-8

[英]saving Java file in UTF-8

When I run this program it gives me a '?' 当我运行该程序时,它给我一个“?” for the unicode code-point . 对于unicode代码点\\ u0508 This is because the default windows character encoding CP-1252 is unable to map this code-point. 这是因为默认的Windows字符编码CP-1252无法映射此代码点。

But when I save this file in Eclipse as 'Text file encoding' = UTF-8 and run this program it gives me the correct output AԈC . 但是,当我在Eclipse中将此文件另存为'文本文件编码'= UTF-8并运行此程序时,它将为我提供正确的输出AԈC

why does this work? 为什么这样做? I mean the java file is saved as UTF-8 but still the underlying windows OS encoding is CP-1252. 我的意思是将Java文件另存为UTF-8,但基础Windows OS编码仍为CP-1252。 My question is similar to, when I try to read a text file in UTF-16 which was originally written in UTF-8, the output is wierd with different box symbols. 我的问题类似于,当我尝试读取最初以UTF-8编写的UTF-16文本文件时,输出结果带有不同的框符号。

public class e {
public static void main(String[] args) {
    System.out.println(System.getProperty("file.encoding"));
    String original = new String("A" + "\u0508" + "C");
    try {
        System.out.println("original = " + original);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Saving the Java source file either as UTF-8 or Windows-1252 shouldn't make any difference, because both encodings encode all the ASCII code-points the same way. 将Java源文件另存为UTF-8或Windows-1252不会有任何区别,因为两种编码都以相同的方式编码所有ASCII码点。 And your source file is only using ASCII characters. 并且您的源文件仅使用ASCII字符。

So, that you should try to find the bug somewhere else. 因此,您应该尝试在其他地方找到该错误。 I suggest to redo the steps you did with care and do the tests over. 我建议重做您仔细执行的步骤并重新进行测试。

The issue is the setting of file.encoding when you run the program, and the destination of System.out. 问题是运行程序时file.encoding的设置以及System.out的目标。 If System.out is an eclipse console, it may well be set to be UTF-8 eclipse console. 如果System.out是一个eclipse控制台,则可以将其设置为UTF-8 eclipse控制台。 If it's just a Windows DOS box, it is a CP1252 code page, and will only display ? 如果只是Windows DOS框,则为CP1252代码页,并且仅显示? in this case. 在这种情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM