To call getResourceAsStream in a static method, we use ClassName.class instead of getClass()
1. In non static method
getClass().getClassLoader().getResourceAsStream("config.properties"))
2. In static method
ClassName.class.class.getClassLoader().getResourceAsStream("config.properties"))
1. Non Static Method
A .properties file in project classpath.
src/main/resources/config.properties
#config file
json.filepath = /home/tvt/workspace/favtuts/data/
FileHelper.java
package com.favtuts.io.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FileHelper {
public static void main(String[] args) {
FileHelper obj = new FileHelper();
System.out.println(obj.getFilePathToSave());
}
public String getFilePathToSave() {
Properties prop = new Properties();
String result = "";
try (InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("config.properties")
) {
prop.load(inputStream);
result = prop.getProperty("json.filepath");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
Output
/home/tvt/workspace/favtuts/data/
2. Static Method
If the method getFilePathToSave() is converted into a static method, the getClass() method will be failed, and prompts Cannot make a static reference to the non-static method getClass() from the type Object
To fix this, update getClass() to ClassName.class
FileHelper.java
package com.favtuts.io.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FileHelper {
public static void main(String[] args) {
// Static Method
System.out.println(getFilePathToSaveStatic());
}
public static String getFilePathToSaveStatic() {
Properties prop = new Properties();
String result = "";
try (InputStream inputStream = FileHelper.class.getClassLoader()
.getResourceAsStream("config.properties")
) {
prop.load(inputStream);
result = prop.getProperty("json.filepath");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
Output
/home/tvt/workspace/favtuts/data/
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-io/utils