-4
File f = new File(System.getProperty("user.home/Downloads"));

这段代码怎么会出现 NPE 错误?

我知道它返回null,但目录在那里......

4

2 回答 2

6

因为

System.getProperty("user.home/Downloads")

返回null,因为没有用 key 设置这样的属性user.home/Downloads

您可能正在寻找

final String fileName = System.getProperty("user.home") + File.saperator + "Downloads";
File f = new File(fileName);
于 2012-11-17T02:55:19.653 回答
0

Properties are collections of <key,value> pairs (both Strings) that can give you information about some predefined system attributes. Which ones are predefined is listed in the documentation of the function System.getProperties. The following keys are defined:

java.version
java.vendor 
java.vendor.url 
java.home 
java.vm.specification.version 
java.vm.specification.vendor 
java.vm.specification.name 
java.vm.version 
java.vm.vendor 
java.vm.name 
java.specification.version 
java.specification.vendor 
java.specification.name 
java.class.version 
java.class.path 
java.library.path 
java.io.tmpdir 
java.compiler 
java.ext.dirs 
os.name 
os.arch 
os.version 
file.separator 
path.separator 
line.separator 
user.name 
user.home 
user.dir

As you can see user.home is in that list, that's why it works perfectly fine to call System.getProperty("user.home");.

However, you are calling the getProperty method with the argument user.home/Downloads -- this is an undefined key, as it is not on the above list.

If you want to append "/Downloads" to the user's home directory, you have to do it outside the getProperty call:

System.getProperty("user.home") + "/Downloads";

This way, you're using a defined key and won't get a NullPointerException.

于 2012-11-17T04:05:58.957 回答