java - 文件字符集
我有一个应用程序,它处理一些文本然后将其保存到文件中。
当我从 NetBeans IDE 运行它时,System.out
和 PrintWriter
都可以正常工作,并且可以正确显示/保存非 ACSII 字符。但是,如果我从 Windows 7 命令行(在本例中使用 cp1250 (中欧) 编码)运行 JAR,屏幕输出和保存的文件就会损坏。
我尝试将 UTF-8
放入 PrintWriter
的构造函数中,但没有帮助......并且它不会影响 System.out
,即使在此之后它也会被损坏。
为什么它在 IDE 中工作,而不是在 cmd.exe
中工作?
我知道 System.out
有一些问题,但为什么输出文件也受到影响?
我该如何解决这个问题?
I have an application, which proccesses some text and then saves it to file.
When I run it from NetBeans IDE, both System.out
and PrintWriter
work correct and non-ACSII characters are displayed/saved correctly. But, if I run the JAR from Windows 7 command line (which uses the cp1250
(central european) encoding in this case) screen output and saved file are broken.
I tried to put UTF-8
to PrintWriter
's constructor, but it didn't help… And it can't affect System.out
, which will be corrupted even after this.
Why is it working in the IDE and not in cmd.exe
?
I would understand that System.out
has some problems, but why is also output file affected?
How can I fix this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚遇到了同样的问题。
实际原因是当您的代码在 NetBeans 环境中运行时,NetBeans 会自动设置系统的属性。
您可以看到,当您使用 NetBeans 运行代码时,下面的代码可能会打印“UTF-8”。但是当你用cmd运行它时,你肯定会看到“cp1256”。
您应该注意到,虽然使用“setProperty”将更改“getProperty”函数的输出,但它不会对输入/输出产生任何影响。 (因为它们都是在调用主函数之前设置的。)
考虑到这个背景,当你想从文件中读取并写入它们时,最好使用下面的代码:
用于读取:
和用于写入(我没有测试过) this):
主要区别在于这些类在其构造函数中获取所需的字符集,但像 FileWrite 和 PrintWrite 这样的类则没有。
我希望这对你有用。
I just had the same problem.
Actual reason of that is because when your code is ran in NetBeans environment, NetBeans automatically sets properties of the system.
You can see that when you run your code with NetBeans, the code below probably prints "UTF-8". But when you run it with cmd, you sure will see "cp1256".
You should notice that while using 'setProperty' will change the output of 'getProperty' function, it will not have any effect on Input/Outputs. (because they are all set before the main function is called.)
Having this background in mind, when you want to read from files and write to them, It's better to use codes below:
For reading:
and for writing (I have not tested this):
the main difference is that these Classes get required Charset in their constructors, but classes like FileWrite and PrintWrite don't.
I hope that works for you.