可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am using the following code to read a properties file:
Properties pro = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().
getResourceAsStream("resources.properties");
pro.load(is);
And when I execute the code I'm getting the following error:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at com.ibm.rqm.integration.RQMUrlUtility.RQMRestClient.getResource(RQMRestClient.java:66)
at com.ibm.rqm.integration.RQMUrlUtility.RQMRestClient.main(RQMRestClient.java:50)
Why am I getting a NullPointerException
? And where should I save the resources.properties
file?
回答1:
It looks like ClassLoader.getResourceAsStream(String name)
returns null
, which then causes Properties.load
to throw NullPointerException
.
Here's an excerpt from documentation:
URL getResource(String name)
: Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.
The name of a resource is a '/'
-separated path name that identifies the resource.
Returns: A URL
object for reading the resource, or null
if:
- the resource could not be found, or
- the invoker doesn't have adequate privileges to get the resource.
See also
- Java Tutorials/Loading Images Using
getResource
- Has examples of where/how to put and access resources in the directory/JAR file
- SDN: Location-Independent Access to Resources
回答2:
Bugfixing is easier if you write more lines, like:
Properties properties = new Properties();
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
InputStream propertiesStream = contextClassLoader.getResourceAsStream("resource.properties");
if (propertiesStream != null) {
properties.load(propertiesStream);
// TODO close the stream
} else {
// Properties file not found!
}
回答3:
I had the same problem and was quite confused as I used it previously in a Sturts application. But the problem was that I didn't understand the type of ClassLoader that Struts returns is different than what Spring returns. And the way i figured it out was i printed out the object that was returned on to the system console like this:
System.out.println(Thread.currentThread().getContextClassLoader());
[
WebappClassLoader
context: /MyProject
delegate: false
repositories:
/WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@1004901
]
It gave me the detail of the object, and in that I found its type to be of WebAppClassLoader which will start looking for files in the WEB-INF/classes/ folder after a build is done. So I went into the that folder and looked for where my file is located so I gave the path accordingly.
In my case it was located in /WEB-INF/classes/META-INF/spring/filename.extension
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/spring/filename.extension");
Voilà!
That fixed it all.
回答4:
Well it depends; As per javadoc ...
The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application...
So if Thread.currentThread().getContextClassLoader()
is in the main() function and you haven't created any thread then it should have the same package as that of the class containing method main. Otherwise it should be present in the class which has created the thread....
回答5:
I had the same problem and I have resolved by doing the following
File file = new File("resources.properties");
System.out.println(file.getAbsolutePath());
and then put "resources.properties" file under that path.
回答6:
I had the same problem and this helped me:
InputStream is;
try {
is = this.getClass().getClassLoader().getResourceAsStream("config.properties");
prop.load(is);
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String pass = prop.getProperty("password");
is.close();
// opening database connection to MySQL server
con = DriverManager.getConnection(url, user, pass);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
回答7:
In my situatioan I get NullPointerException in this code
LogManager.getLogManager()
.readConfiguration(MyClass.class.getResourceAsStream("config/logging.properties"));
I changed
LogManager.getLogManager().readConfiguration(AzLotteryTerm.class.getClassLoader().getResourceAsStream("config/logging.properties"));
and now works ok!
回答8:
I had this problem with a third-party program and it turned out that I needed to include .
in the classpath so that the program could read a local properties file in the current working directory.
回答9:
Many seem to have this problem and like me they give up after sometime. Here is what I had to get this working. The trick here to use relative path for file lookup is to make sure your classes folder contains resources files along with src files. Here is what I ended up doing.
1) If you are using eclipse make sure you proper .classpath setting present and do PROJECT CLEAN to see the resources files get generated under /classes. Notice the classpath-entries below for resource files place under src/main/resource
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry including="**/*.java" kind="src" output="target/test-classes" path="src/test/java"/>
<classpathentry including="**/*.java" kind="src" path="src/main/java"/>
<classpathentry kind="var" path="M2_REPO/javax/mail/mail/1.4.4/mail-1.4.4.jar"/>
<classpathentry kind="var" path="M2_REPO/javax/activation/activation/1.1/activation-1.1.jar"/>
<classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
2) If you are using maven as well make sure you configure your pom.xml as per the https://maven.apache.org/guides/introduction/introduction-to-the-pom.html and do mvn clean install to see the files under target/classes
3) Once you have got the resource files under /classes the next thing to do in java is the following. Don't forget to have the forward slash.
try {
properties.load(getClass().getResourceAsStream("/mail-config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
I could have added some images but did not have points. :)
回答10:
Perhaps, I have plucked all my hairs out and going then I have found this solution out:
Properties dbParamProperties = new Properties();
InputStream input = null;
try {
String pathOfAbsolute = this.getClass().getProtectionDomain().getCodeSource().getLocation().toString();
String propertiesFilePath = pathOfAbsolute+"/properties/conf.properties";
propertiesFilePath = propertiesFilePath.replace("file:/", "").replace("/", "\\");
System.out.println(pathOfAbsolute);
System.out.println(propertiesFilePath);
Paths.get(new URI(pathOfAbsolute));
input = ClassLoader.getSystemResourceAsStream(propertiesFilePath);
input = new FileInputStream(propertiesFilePath);
dbParamProperties.load( input );
dbUID = dbParamProperties.getProperty("userName");
dbURL = dbParamProperties.getProperty("hosturl");
dbPWD = dbParamProperties.getProperty("password");
dbPort = dbParamProperties.getProperty("port");
dbSID = dbParamProperties.getProperty("servicenameorsid");
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception ex){
ex.printStackTrace();
}