java项目中的静态文件读取

文件读取方法一(本地可用)

        ClassPathResource classPathResource = new ClassPathResource("img.png");
        //获取文件
        File file = classPathResource.getFile();
        //获取文件流
        FileInputStream inputStream = new FileInputStream(file);
  • 该方法在本地可用。但是在线上服务将读取失败!!!

文件读取方法二 (线上服务可用)

        //获得文件流时,因为读取的文件是在打好jar文件里面,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
        //ResourcePatternResolver的实现方法,可以匹配到各种部署时的各种文件类型例如war,jar,zip等等findPathMatchingResources
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("img.png");
        Resource resource = resources[0];
        if (resource == null) {
            throw new BizException("图片读取失败!");
        }
        String tempPath = System.getProperty("java.io.tmpdir") + "tomcat_" + System.currentTimeMillis();
        String tempFile = tempPath + File.separator + "img.png";
        File file = new File(tempPath);
        if (!file.exists()) {
            file.mkdir();
        }
        // 将jar中的文件拷贝到临时文件夹下面
        ByteStreams.copy(resource.getInputStream(), new FileOutputStream(new File(tempFile)));
       
  • 该方法将jar包中的文件以字节流读取存在相应的临时文件目录下,可以正常进行线上使用
  • new FileInputStream(new File(tempPath + File.separator + “img.png”)

文件存放目录如下

在这里插入图片描述

文件目录读取

        ClassPathResource classPathResource = new ClassPathResource("msyh.ttf");
        String path = classPathResource.getURL().getPath();
        String pathStr = path.substring(0, path.lastIndexOf("/"));
        FontSettings.setFontsFolder(pathStr, true);

项目中的jar包读取

<!--  方法一  --->
        <dependency>
            <groupId>xiaomi</groupId>
            <artifactId>xiaomi</artifactId>
            <version>1.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/xxx.jar</systemPath>
        </dependency>

<!--  方法二  --->
        <dependency>
            <groupId>xiaomi</groupId>
            <artifactId>xiaomi</artifactId>
            <version>1.2</version>
            <scope>system</scope>
      <systemPath>${project.basedir}/lib/xxxx.jar</systemPath>
        </dependency>
  • 方法2为项目中之前使用,项目部署上去回报错,原因是打包之后并没有带到服务器之中,随后改为方法一,将文件存放在resource当中可以使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值