当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How come this code gets an NPE?

问题描述:

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

How come this code gets an NPE error?

I know it returns null, but the directory is there...

网友答案:

because

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

returns null, because there is no such propery set with key user.home/Downloads

You may be looking for

final String fileName = System.getProperty("user.home") + File.saperator + "Downloads";
File f = new File(fileName);
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: