Java 读取 Properties 文件的几种方法
在 Java 中读取 properties 文件有几种常见方法,以下是详细说明:

(图片来源网络,侵删)
使用 java.util.Properties 类(最常用)
import java.io.InputStream;
import java.util.Properties;
public class PropertyReader {
public static void main(String[] args) {
Properties prop = new Properties();
try (InputStream input = PropertyReader.class.getClassLoader().getResourceAsStream("config.properties")) {
if (input == null) {
System.out.println("Sorry, unable to find config.properties");
return;
}
prop.load(input);
// 获取属性值
String dbUrl = prop.getProperty("database.url");
String dbUser = prop.getProperty("database.user");
String dbPassword = prop.getProperty("database.password");
System.out.println("Database URL: " + dbUrl);
System.out.println("Database User: " + dbUser);
System.out.println("Database Password: " + dbPassword);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
使用 java.util.ResourceBundle 类(适合国际化)
import java.util.ResourceBundle;
public class ResourceBundleExample {
public static void main(String[] args) {
// 不需要扩展名,也不需要路径(假设在classpath根目录)
ResourceBundle rb = ResourceBundle.getBundle("config");
String dbUrl = rb.getString("database.url");
String dbUser = rb.getString("database.user");
System.out.println("Database URL: " + dbUrl);
System.out.println("Database User: " + dbUser);
}
}
使用 Spring Framework 的 @Value 注解(Spring环境)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class SpringPropertyReader {
@Value("${database.url}")
private String dbUrl;
@Value("${database.user}")
private String dbUser;
public void printProperties() {
System.out.println("Database URL: " + dbUrl);
System.out.println("Database User: " + dbUser);
}
}
使用 Java 7 的 try-with-resources 和 Path(NIO方式)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class NioPropertyReader {
public static void main(String[] args) {
Properties prop = new Properties();
Path path = Paths.get("config.properties");
try {
prop.load(Files.newInputStream(path));
String dbUrl = prop.getProperty("database.url");
System.out.println("Database URL: " + dbUrl);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
注意事项
-
文件位置:通常将 properties 文件放在
src/main/resources目录下,这样它会被自动包含在 classpath 中。 -
文件名:properties 文件通常以
.properties为扩展名。 -
编码问题:properties 文件包含非 ASCII 字符,确保文件使用 UTF-8 编码。
-
异常处理:始终处理可能出现的
IOException和NullPointerException。
(图片来源网络,侵删) -
类加载器:使用
getClassLoader().getResourceAsStream()时,路径是相对于 classpath 根目录的。 -
ResourceBundle:使用
ResourceBundle时,不需要扩展名,并且它会自动处理不同语言环境的变体(如config_en.properties)。
选择哪种方法取决于你的具体需求和应用场景,对于简单的 Java 应用,第一种方法是最直接和常用的。

(图片来源网络,侵删)
