zoukankan      html  css  js  c++  java
  • ClassLoader读取文件,springboot打jar包后读取不到

    jar:file:/D:/test/test/.metadata/.plugins/org.eclipse.wst.server.core/test/test/test/WEB-INF/lib/test-0.0.1-SNAPSHOT.jar!/ca.crt

    在你的项目中可能经常会使用ClassLoader.getSystemResourceAsStream等方法来读取一个文件内容,使用properties来读取。
    但是当你打包后会发现你程序出现了问题,这个时候怎么办呢?
    **解决**可以尝试一下以下的代码来获取文件,内容可自行修改,逻辑比较简单,就是获取相对地址然后得到文件

       //s是地址+文件名 from fhadmin.cn
       private File loadNewFromResources(String s) {
           File file = new File( s);
    
            try {
                if (!file.exists()) {
                    file.createNewFile();
    
                    InputStream fileInput = SampleServerStartup.class.getClassLoader().getResourceAsStream( s);
    
                    //from fhadmin.cn
                    //file = File.createTempFile(s,"");
                    System.out.println(file.getPath());
                    System.out.println(file.getCanonicalPath());
                    System.out.println(file.getName());
                    //System.out.println("length:"+fileInput.available());
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;
    
                    while ((len = fileInput.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                    fileInput.close();
    
                    //System.out.println(content); //from fhadmin.cn
    
                    FileOutputStream fileout = new FileOutputStream(file);
                    baos.writeTo(fileout);
    
                    baos.close();
                    fileout.close();
    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file;
        }

    为什么要这样处理,因为在你打包后通过File f=new File(“上述路径—相对路径”);来获取文件时会发现FileNotFoundException

    可以通过getResourceAsStream()读取到文件流—只可读取

    因为这不是文件资源定位符的格式 (在jar中资源有其专门的URL格式为: jar:!/{entry} )。
    如果jar包中的类源代码用File f=new File(相对路径);的形式,是找不到文件资源的。

  • 相关阅读:
    LeetCode——二叉搜索树中的中序后继 II
    一加 2020.10.13 笔试
    携程 2020.10.13 笔试
    中科曙光 2020.10.12 面试
    58 2020.10.11 笔试
    华为 2020.10.11 面试
    LeetCode——二叉搜索树中的顺序后继
    健网未来 2020.10.10 面试
    波特率
    PGA基础知识极简教程(4)从FIFO设计讲起之异步FIFO篇
  • 原文地址:https://www.cnblogs.com/teacher11/p/15193209.html
Copyright © 2011-2022 走看看