加载properties文件

本文介绍如何使用JUnit进行文件流操作及异常处理,包括文件输入流的创建、加载属性文件并打印属性值,同时处理文件不存在和IO异常。
package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.logging.LogFactory;


public class JunitTest {
    org.apache.commons.logging.Log log = LogFactory.getLog(JunitTest.class);
    public void testLoadFile(){
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("C:\\config.properties");
            java.util.Properties properties = new java.util.Properties();
            properties.load(fileInputStream);
            Object value = properties.get("a");
            System.out.println(value.toString());
        } catch (FileNotFoundException e) {
            try {
                fileInputStream.close();
            } catch (IOException e1) {
                log.error("JunitTest IOException "+e1);
            }
        } catch (IOException e) {
            try {
                fileInputStream.close();
            } catch (IOException e1) {
                log.error("JunitTest IOException "+e1);
            }
        }

    }

}
<think>我们正在讨论Java中使用类加载加载properties文件的方法。根据引用内容,有几种常见方式,我将总结并给出清晰步骤。 关键点:使用类加载器(ClassLoader)来获取输入流,然后通过Properties对象加载。 步骤: 1. 获取当前类的类加载器(ClassLoader)。 2. 使用类加载器的`getResourceAsStream`方法获取配置文件的输入流。注意:配置文件需放在类路径下(如src目录,对于Maven项目通常在resources目录)。 3. 创建Properties对象。 4. 使用Properties的`load`方法加载输入流。 5. 通过`getProperty`方法获取配置值。 示例代码(参考引用[2]): ```java import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class LoadPropertiesDemo { public static void main(String[] args) throws IOException { // 1. 获取类加载器 ClassLoader classLoader = LoadPropertiesDemo.class.getClassLoader(); // 2. 使用类加载加载配置文件(假设配置文件名为config.properties,位于类路径根目录) InputStream inputStream = classLoader.getResourceAsStream("config.properties"); // 3. 创建Properties对象 Properties properties = new Properties(); // 4. 加载输入流 properties.load(inputStream); // 5. 获取配置值 String value = properties.getProperty("key"); System.out.println(value); } } ``` 注意事项: - 配置文件路径:如果配置文件在包内,则需要使用全路径(如:`com/example/config.properties`)。 - 空指针异常:如果`getResourceAsStream`返回null,说明未找到文件,请检查文件名和路径。 - 资源关闭:在实际应用中,应使用try-with-resources确保流关闭,避免资源泄漏。 改进版(使用try-with-resources): ```java import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class LoadPropertiesDemo { public static void main(String[] args) { // 使用try-with-resources自动关闭流 try (InputStream inputStream = LoadPropertiesDemo.class.getClassLoader().getResourceAsStream("config.properties")) { if (inputStream == null) { System.out.println("配置文件未找到!"); return; } Properties properties = new Properties(); properties.load(inputStream); String value = properties.getProperty("key"); System.out.println(value); } catch (IOException e) { e.printStackTrace(); } } } ``` 其他方式(参考引用): 除了使用类加载器,还可以: - 使用`Class`的`getResourceAsStream`方法(相对路径,以'/'开头表示从类路径根目录开始)。 - 使用`ResourceBundle`(仅适用于.properties文件,且不需要指定后缀)。 例如,使用`Class`的`getResourceAsStream`: ```java // 从类路径根目录加载(注意前面的斜杠) InputStream in = MyClass.class.getResourceAsStream("/config.properties"); // 或者相对路径(相对于当前类所在包) InputStream in = MyClass.class.getResourceAsStream("config.properties"); // 在同一个包内 ``` 总结推荐:使用类加载器(`ClassLoader`)的方式是常见且推荐的做法,尤其当文件在类路径根目录时。 §§相关问题§§ 1. 如何解决Java加载properties文件时出现的空指针异常? 2. 在Spring框架中,如何更优雅地加载properties文件? 3. 除了类加载器,还有哪些方式可以加载Java中的配置文件? 4. 如何加载非类路径下的properties文件? 5. 在Web应用中(如Servlet),加载properties文件有什么不同?</think>### Java加载加载 Properties 文件的方法 在 Java 中,使用类加载加载 properties 文件是一种高效的方式,尤其适用于配置文件位于类路径(classpath)下的场景。以下是详细步骤和示例: --- #### **核心步骤** 1. **获取类加载器** 通过当前类的 `Class` 对象获取类加载器: ```java ClassLoader classLoader = YourClassName.class.getClassLoader(); ``` 2. **获取文件输入流** 使用类加载器的 `getResourceAsStream()` 方法加载文件: ```java InputStream inputStream = classLoader.getResourceAsStream("文件路径"); ``` - **路径规则**: - 文件在类路径根目录:直接写文件名(如 `"config.properties"`) - 文件在包内:使用包路径(如 `"com/example/config.properties"`) 3. **加载 Properties 对象** 创建 `Properties` 对象并加载输入流: ```java Properties properties = new Properties(); properties.load(inputStream); ``` 4. **读取配置项** 通过 `getProperty()` 获取值: ```java String value = properties.getProperty("key"); ``` --- #### **完整示例代码** ```java import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertiesLoader { public static void main(String[] args) throws IOException { // 1. 获取类加载器 ClassLoader classLoader = PropertiesLoader.class.getClassLoader(); // 2. 加载配置文件(假设文件在src/main/resources目录下) try (InputStream input = classLoader.getResourceAsStream("app.properties")) { if (input == null) { System.err.println("配置文件未找到!"); return; } // 3. 加载Properties对象 Properties props = new Properties(); props.load(input); // 4. 读取配置 String username = props.getProperty("db.username"); String password = props.getProperty("db.password"); System.out.println("用户名: " + username); System.out.println("密码: " + password); } } } ``` --- #### **关键注意事项** 1. **文件位置** - 配置文件必须位于类路径中(如 Maven 项目的 `src/main/resources` 目录)[^2][^3]。 - 路径错误会导致 `inputStream` 为 `null`(需空指针检查)。 2. **路径格式** - 使用 `/` 分隔目录(非 `\`),如 `"com/example/config.properties"`。 3. **资源关闭** - 使用 **try-with-resources**(如上例)自动关闭流,避免资源泄漏[^2]。 4. **特殊场景** - **Web 项目**:类加载器逻辑相同,但配置文件通常放在 `WEB-INF/classes` 目录。 - **Spring 框架**:推荐使用 `@PropertySource` 注解更便捷地加载配置。 --- #### **其他加载方式对比** | 方法 | 优点 | 缺点 | |---------------------|--------------------------|--------------------------| | 类加载器 | 灵活,支持任意类路径文件 | 需手动处理输入流 | | `ResourceBundle` | 无需处理流,自动加载 | 仅支持 properties 文件 | | `FileInputStream` | 直接指定物理路径 | 路径硬编码,移植性差 | > 类加载器方式是**最推荐**的跨平台方案,尤其适合打包后的 JAR/WAR 文件[^3][^5]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值