读取Jar包外部文件的几种方式

本文详细介绍了在Java程序中如何在Jar包内部读取外部文件,包括ClassLoader.getResourceAsStream()、绝对路径、URLClassLoader和Spring框架的Resource,以解决部署到服务器时的文件读取问题。

在Java应用程序中,有时候需要在Jar包内部的代码中读取Jar包外部的文件。有很多小伙伴们在本地运行的时候都正常,但是部署到服务器上就各种读取文件失败,下面就介绍几种常见的方式,结合场景和代码进行详细说明,大家可以根据自己的场景使用合适的方式。

1. ClassLoader.getResourceAsStream()

ClassLoader.getResourceAsStream()方法允许从类路径下获取资源,包括Jar包外部的文件。

public class FileReader {
    public String readExternalFile() {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("externalFile.txt");
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error reading external file";
        }
    }
}

2. 使用绝对路径

使用绝对路径是一种直接的方式,但要确保文件路径是正确的,且相对路径是相对于执行Java命令的当前工作目录。

public class FileReader {
    public String readExternalFile() {
        String externalFilePath = "/path/to/externalFile.txt";
        try (BufferedReader reader = new BufferedReader(new FileReader(externalFilePath))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error reading external file";
        }
    }
}

3. 使用URLClassLoader

通过URLClassLoader加载Jar包外部的文件,这样可以使用绝对路径或相对路径。

import java.net.URL;
import java.net.URLClassLoader;

public class FileReader {
    public String readExternalFile() {
        String externalFilePath = "/app/config/externalFile.txt";
        try {
            URL externalFileUrl = new URL("file:" + externalFilePath);
            URLClassLoader classLoader = new URLClassLoader(new URL[]{externalFileUrl});
            InputStream inputStream = classLoader.getResourceAsStream("externalFile.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error reading external file";
        }
    }
}

4. 使用Spring框架的Resource

Spring框架提供了org.springframework.core.io.Resource接口,通过org.springframework.core.io.DefaultResourceLoader加载Jar包外部的文件。

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

public class FileReader {
    public String readExternalFile() {
        String externalFilePath = "/path/to/externalFile.txt";
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("file:" + externalFilePath);
        try (InputStream inputStream = resource.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error reading external file";
        }
    }
}

 

5. 总结

本文介绍了几种读取Jar包外部文件的常见方式,包括使用ClassLoader.getResourceAsStream()、使用绝对路径、使用URLClassLoader、以及使用Spring框架的Resource。在选择使用哪种方式时,需要根据具体的场景和需求进行选择,确保代码的可维护性和可移植性。

### 如何让Spring Boot JAR引用外部配置文件 在Spring Boot项目中,可以通过多种方式实现JAR外部配置文件的引用。以下是几种常见的方法及其具体实现: #### 方法一:通过命令行参数指定外部配置文件位置 可以使用`--spring.config.location`参数来指定外部配置文件的位置。此参数允许开发者覆盖默认的配置文件路径。 例如,在运行JAR时,可以通过如下命令加载外部配置文件: ```bash java -jar myproject.jar --spring.config.location=/path/to/config/application.yml ``` 这种方式支持多个配置文件的同时加载,并按照优先级顺序解析配置项[^3]。 #### 方法二:设置环境变量或系统属性 除了命令行参数外,还可以通过环境变量或系统属性的方式指定外部配置文件的位置。例如,可以在启动脚本中定义以下内容: ```bash export SPRING_CONFIG_LOCATION=/path/to/config/ java -jar myproject.jar ``` 或者直接在Java虚拟机选项中传递系统属性: ```bash java -Dspring.config.location=/path/to/config/ -jar myproject.jar ``` 这种方法同样适用于动态调整配置文件路径的需求[^4]。 #### 方法三:利用Spring Boot内置的配置文件加载机制 Spring Boot 提供了一套灵活的配置文件加载机制,其中外部配置文件具有较高的优先级。当存在同名配置项时,外部配置会覆盖内部配置中的值。具体的加载顺序遵循官方文档所描述的规则[^1]。 为了确保外部配置生效,建议将外部配置文件放置于标准目录下(如当前工作目录下的`config`子目录),这样无需额外指定路径即可自动加载。 #### 方法四:自定义配置逻辑 如果以上方法无法满足特定需求,则可通过编程手段扩展配置加载功能。例如,在应用启动阶段显式引入外部资源: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { System.setProperty("spring.config.additional-location", "/path/to/custom-config/"); SpringApplication.run(MyApplication.class, args); } } ``` 此处设置了`spring.config.additional-location`属性,用于补充其他可能存在的配置源[^2]。 --- ### 注意事项 - **优先级控制**:不同来源的配置可能会发生冲突,因此需了解并合理规划各层次之间的优先关系。 - **兼容性测试**:针对目标环境中可能出现的各种情况充分验证方案的有效性和稳定性。 - **安全性考量**:敏感数据不应暴露在外置明文中;必要时采用加密存储与解密读取策略。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Memory_2020

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值