简体   繁体   English

System.setProperty无法在Java中用于file.encoding

[英]System.setProperty not working for file.encoding in Java

I have this simple program where Im trying to create a txt file with UTF-8 format. 我有这个简单的程序,我试图创建UTF-8格式的txt文件。 However, I see that the file is not encoded with UTF-8 but shows the encoding is set to ANSI. 但是,我看到该文件未使用UTF-8编码,但显示编码已设置为ANSI。 Below is the output. 以下是输出。 Can you please help. 你能帮忙吗?

public class fileCreate {
   public static void main(String[] args) {
      try {
             System.out.println("Before encoding: "+System.getProperty("file.encoding"));
             System.setProperty("file.encoding","UTF-8");
             System.out.println("After encoding: "+System.getProperty("file.encoding")); 

             File file = new File("C:/tmp/myfile_UTF-8.txt");

             if(file.createNewFile())System.out.println("Success!");
               else System.out.println ("Error, file already exists.");
          }
          catch(IOException ioe) {
          ioe.printStackTrace();
          }
      }
   }

Output: 输出:

Before encoding: Cp1252 编码前:Cp1252

After encoding: UTF-8 编码后:UTF-8

Success! 成功!

When you create a new file, it is initially empty. 创建新文件时,它最初是空的。 "Encoding" is not a property of the file, it is how you interpret its content bytes. “编码”不是文件的属性,而是您解释其内容字节的方式。 That is also why you have to specify the encoding before reading and writing, because it is not stored anywhere. 这也是为什么在读写之前必须指定编码的原因,因为它没有存储在任何地方。

Without content, the encoding is kind of undefined. 没有内容,编码是不确定的。 Your editor probably picks its first guess, which might be ASCII. 您的编辑器可能会选择第一个猜测,可能是ASCII。 But empty content can probably be decoded with any encoding. 但是,空内容可以使用任何编码进行解码。

If you write some text to the file in your code, it will be encoded in UTF-8. 如果您在代码中向文件中写入一些文本,则它将以UTF-8编码。 Your editor will then show its encoding as such too (provided it is a good one and can detect it correctly). 然后,您的编辑器也将显示其编码(前提是该编码很好,并且可以正确检测到它)。

您可以使用以下代码创建UTF-8文件

PrintWriter out1 = new PrintWriter(new File("C:/tmp/myfile_UTF-8.txt"), "UTF-8");

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

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