jar包访问resources下资源

  • Post author:
  • Post category:其他


须知

1、当项目打成jar包后,无法通过

File file = new File("无论你通过任何途径获取到的resources的路径");

这种形式访问,因为打成jar包后,

jar包是一个整体文件

,其中每个文件都是jar包的某段字节码。

2、通过解压缩的形式,我们发现,并不存在resources目录,其中文件放在classes目录下(.java文件,编译后为.class文件也放在此目录下),如下图所示。

解决方法

一、我只需要访问properties文件中的某一配置信息

基于Spring boot,采用

@PropertySource(value = “classpath:xxx.properties”)

结合

@Value

即可。

参考链接:

https://blog.csdn.net/wenroudeni/article/details/109484374

二、我需要访问resources下的文件作为InputStream的形式进行操作。

采用

InputStream in = new ClassPathResource("默认从resources下获取,填static\hello.properties即可,若是以\开口,则从项目路径下获取").getInputStream();//获得hello.properties文件的流。

另外一种getResourceAsStream则请参考:

https://www.cnblogs.com/macwhirr/p/8116583.html

一、我一定要通过File file = new File(“path”)的形式访问

先看一下代码结构,本次代码基于须知第一条,既然jar包中的每个文件是段字节码,那么只需将字节码生成文件即可访问。

代码:

    @GetMapping("/hello")
    public String  hello() {//返回因此方法生成的hello.properties文件在服务器上的路径
        String result = "";
        try {
            String path = System.getProperty("user.dir");//项目路径
            String separator = System.getProperty("file.separator");//windows为\,linux为/
            String resourcesPath = "static"+separator+"hello.properties";//从resources开始的路径 本例中为:static\hello.properties
            InputStream in = new ClassPathResource(resourcesPath).getInputStream();//获得hello.properties文件的流
            File file = new File(path+separator+resourcesPath);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            if (!file.exists()){
                file.createNewFile();
            }
            writeToLocal(path+separator+resourcesPath,in);//将文件写到本地
            //获取本地文件
            result = file.getAbsolutePath();
        } catch (IOException e) {
            result = e.getMessage();
        }
        return result;
    }

    /**
     * 将输入流写到本地
     * @param filePath 本地文件路径
     * @param in 输入流
     */
    private static void writeToLocal(String filePath,InputStream in){
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            byte[] buffer = new byte[1024];
            int index;
            while ((index = in.read(buffer)) != -1){
                out.write(buffer,0,index);
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

最终在linux中运行的结果如下:

希望对你有所帮助。

另外,若是想简单了解为何需要反射,请浏览以往文章。

JAVA为什么要反射?(小白向)



版权声明:本文为qq_40304825原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。