在Java项目中,通常会将properties
文件放在src/main/resources
目录下,以便它们能够被打包进最终的jar或war文件中,并且能够通过类路径(classpath)访问。要从类路径中加载properties
文件,可以使用Class.getResourceAsStream()
或ClassLoader.getResourceAsStream()
方法。以下是使用这两种方法之一来加载并读取resources
目录下的config.properties
文件内容的示例:
使用Class.getResourceAsStream()
如果你在某个类中执行此操作,可以直接使用当前类的类加载器:
import java.io.InputStream;
import java.util.Properties;
public class PropertiesFromResourcesExample {
public static void main(String[] args) {
// 获取config.properties文件的输入流
InputStream inputStream = PropertiesFromResourcesExample.class.getResourceAsStream("/config.properties");
if (inputStream != null) {
Properties prop = new Properties();
try {
// 加载properties文件
prop.load(inputStream);
// 读取并打印属性值
String username = prop.getProperty("username");
System.out.println("Username: " + username);
// 记得关闭输入流
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.err.println("Unable to find config.properties on classpath.");
}
}
}
注意路径字符串前的斜杠/
,这表示从类路径的根开始查找。如果没有这个斜杠,则路径被视为相对于调用类的位置。
使用ClassLoader.getResourceAsStream()
如果你更倾向于使用类加载器直接:
import java.io.InputStream;
import java.util.Properties;
public class PropertiesFromResourcesExample {
public static void main(String[] args) {
// 获取系统类加载器
InputStream inputStream = PropertiesFromResourcesExample.class.getClassLoader().getResourceAsStream("config.properties");
if (inputStream != null) {
Properties prop = new Properties();
try {
// 加载properties文件
prop.load(inputStream);
// 读取并打印属性值
String username = prop.getProperty("username");
System.out.println("Username: " + username);
// 关闭输入流
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.err.println("Unable to find config.properties on classpath.");
}
}
}
这里没有前导斜杠,因为getResourceAsStream()
默认从类路径根开始搜索。两种方法都是有效的,可以根据具体情况选择使用。