set a system property
-D后面需要跟一个键值对,作用是设置一项系统属性
对-Dfile.encoding=UTF-8来说就是设置系统属性file.encoding为UTF-8
那么file.encoding什么意思?字面意思为文件编码。
搜索java源码,只能找到4个文件中包含file.encoding的文件,也就是说只有四个文件调用了file.encoding这个属性。
在java.nio.charset包中的Charset.java中。这段话的意思说的很明确了,简单说就是默认字符集是在java虚拟机启动时决定的,依赖于java虚拟机所在的操作系统的区域以及字符集。
代码中可以看到,默认字符集就是从file.encoding这个属性中获取的。个人感觉这个是最重要的一个因素。下面的三个可以看看。
/**
* Returns the default charset of this Java virtual machine.
*
*
The default charset is determined during virtual-machine startup and
* typically depends upon the locale and charset of the underlying
* operating system.
*
* @return A charset object for the default charset
*
* @since 1.5
*/
public static Charset defaultCharset() {
if (defaultCharset == null) {
synchronized (Charset.class) {
java.security.PrivilegedAction pa =
new GetPropertyAction("file.encoding");
String csn = (String)AccessController.doPrivileged(pa);
Charset cs = lookup(csn);
if (cs != null)
defaultCharset = cs;
else
defaultCharset = forName("UTF-8");
}
}
return defaultCharset;
}
在java.net包中的URLEncoder.java中的static块里面:
dfltEncName = (String)AccessController.doPrivileged (
new GetPropertyAction("file.encoding")
);
在javax.print包中的DocFlavor.java
static {
hostEncoding =
(String)java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("file.encoding"));
}
在com.sun.org.apache.xml.internal.serializer包中的Encodings
// Get the default system character encoding. This may be
// incorrect if they passed in a writer, but right now there
// seems to be no way to get the encoding from a writer.
encoding = System.getProperty("file.encoding", "UTF8");
另外另一个网友的博客上面看到的:
http://yaojingguo.blogspot.com/2009/02/javas-fileencoding-property-on-windows.html
Java's file.encoding property on Windows platfor
This property is used for the default encoding in Java, all readers and writers would default to using this property. file.encoding is set to the default locale of Windows operationg system since Java 1.4.2. System.getProperty("file.encoding") can be used to access this property. Code such as System.setProperty("file.encoding", "UTF-8") can be used to change this property. However, the default encoding can be not changed dynamically even this property can be changed. So the conclusion is that the default encoding can't change after JVM starts. java -dfile.encoding=UTF-8 can be used to set the default encoding when starting a JVM. I have searched for this option Java official documentation. But I can't find it.