【已解决】在linux部署出现java文件操作报错:java.io.FileNotFoundException

1.报错场景:


其中的 ip2region.xdb 文件是放在 resources 文件夹中的,然后在一个工具类里面读取这个文件,在开发环境中的是这样读取的:
 

            ClassPathResource resource = new ClassPathResource("ip2region.xdb");
            //获取真实文件路径
            String path = resource.getURL().getPath();
            byte[] cBuff = Searcher.loadContentFromFile(path);

然后部署到linux上后,就出现了错误,报 java.io.FileNotFoundException 

2.解决方法:

            ClassPathResource resource = new ClassPathResource("ip2region.xdb");
            InputStream inputStream = resource.getInputStream();
            byte[] bytes = IOUtils.toByteArray(inputStream);

在部署环境,要使用 InputStream inputStream = resource.getInputStream(); 这个方法

3.用java读取linux系统上的指定文件

File file = new File("/usr/webapps/MP/ip2region.xdb");
            if (file.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
            }
            if (file.isFile()) {
                System.out.println("是一个文件");
            } else {
                System.out.println("不是一个文件");
            }
            if (file.canRead()) {
                System.out.println("可读");
            } else {
                System.out.println("不可读");
            }
            if (file.canWrite()) {
                System.out.println("可写");
            } else {
                System.out.println("不可写");
            }



 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年12月8日
下一篇 2023年12月8日

相关推荐