通过命令行和代码设置系统属性之间有什么区别? [英] What is the difference between setting system property from command line and code?

查看:148
本文介绍了通过命令行和代码设置系统属性之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题所在:我的代码中有一些中文,并且正在将其写入sqlite.

Here's the problem: I got some Chinese in my code, and I'm writing it into sqlite.

当我在eclipse中运行程序并从sqlite中读取字符串时,它运行良好.但是,当我将项目打包到jar中并在命令行中运行它时.从sqlite读取的中文字符串不可读.

When I run my program in eclipse and read the string out of sqlite, it just works fine. But when I packaged the project to a jar and run it in command line. The Chinese string which is read out of sqlite is unreadable.

经过一些试验,我知道问题出在file.encoding系统属性中.当我使用命令java -Dfile.encoding=UTF-8 -jar TK.jar运行jar时,它可以很好地与中文单词配合使用,但是,如果我在代码中设置系统属性,例如:System.setProperty("file.encoding", "UTF-8");,它将无法正常工作.

After some trials, I know that the problem lies in the file.encoding system property. When I run the jar using command: java -Dfile.encoding=UTF-8 -jar TK.jar, it works fine with Chinese word, But if I set the system property in code like: System.setProperty("file.encoding", "UTF-8");, it won't work.

那么,从命令行和代码设置系统属性之间有什么区别?谁能告诉我如何在代码中设置file.encoding系统属性?

So, What is the difference between setting the system property from command line and code? And could anyone tell me how to set file.encoding system property in code?

非常感谢!

总结:

请记住在使用String.getBytes()new String()时添加字符集,以避免在不同环境中运行程序时中文或日语的不可读输出.

Remember to add charset when using String.getBytes() as well as new String() in order to avoid unreadable output from Chinese or Japanese when running program in different environment.

推荐答案

在代码中的某些地方,您可能依赖于默认字符集UTF-8.例如,当您在不指定字符集的情况下调用String.getBytes()时,Java将使用默认字符集.如果您始终需要UTF-8,则在调用String.getBytes()时指定此名称:

Somewhere in your code, you are probably relying on the default character set being UTF-8. For example, when you call String.getBytes() without specifying a character set, Java will use the default character set. If you always want UTF-8, then specify this when calling String.getBytes():

byte[] utf8bytes = text.getBytes("UTF-8");

此外,如果要读取具有特定字符编码的文件,请指定字符编码,而不要依赖默认设置.例如:

Also, if you want to read a file with a specific character encoding, then specify the character encoding rather than relying on the default setting. For example:

InputStream is = new FileInputStream("utf8file.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

// Read text, file will be read as UTF-8
String line = in.readLine();

in.close();

这篇关于通过命令行和代码设置系统属性之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆