好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

springboot读取文件,打成jar包后访问不到的解决

springboot读取文件,打成jar包后访问不到

最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。

文件在resources下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

public void test() {

   List<String> names = new ArrayList<>();

   InputStreamReader read = null ;

   try {

    ClassPathResource resource = new ClassPathResource( "name.txt" );

 

    InputStream inputStream = resource.getInputStream();

    read = new InputStreamReader(inputStream, "utf-8" );

    BufferedReader bufferedReader = new BufferedReader(read);

    String txt = null ;

    while ((txt = bufferedReader.readLine()) != null ) {

     if (StringUtils.isNotBlank(txt)) {

      names.add(txt);

     }

    }

   } catch (Exception e) {

    e.printStackTrace();

   } finally {

    if (read != null ) {

     try {

      read.close();

     } catch (IOException e) {

      e.printStackTrace();

     }

    }

   }

  }

springboot打jar包后台无法访问静态文件夹

1.ResourceUtils

平常我们写spring boot 项目的时候偶尔会在后台用到classpath 底下的文件,一般我们都是这样写的

?

1

File file = ResourceUtils.getFile( "classpath:static/image/image" );

这样情况下本来是没啥问题的。但是用 打jar 包 运行以后就会找不到这个文件。

Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。

对于这种情况。有时候会把项目文档放到项目外边,但是这样很容易把这些东西误删除掉。

2.ClassPathResource

?

1

2

ClassPathResource cpr = new ClassPathResource( "static/image/image/kpg" );

InputStream in = cpr.getInputStream();

3. ResourceLoader

?

1

2

3

4

5

6

public class ResourceRenderer {

  public static InputStream resourceLoader(String fileFullPath) throws IOException {

         ResourceLoader resourceLoader = new DefaultResourceLoader();

         return resourceLoader.getResource(fileFullPath).getInputStream();

     }

}

用法

?

1

InputStream in = ResourceRenderer.resourceLoader( "classpath:static/image/image" );

这样就完美的解决了jar包底下路径无法访问的问题。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/WoddenFish/article/details/86161918

查看更多关于springboot读取文件,打成jar包后访问不到的解决的详细内容...

  阅读:19次