Springboot后台打包成jar后成功读取后台根目录文件

有时间Springboot后台项目打成jar包后,运行时不能读取根目录文件,报错。可能是window环境和linux环境不同,所以要要一种比较通用的读取后台外部文件的办法。


    @RequestMapping(value = "/file", method = RequestMethod.GET)
    public ResultJson getFileByDirectory(@RequestParam String fileDirectory){
        byte[] buffer = null;
        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
//                System.err.println("path" + path.getAbsolutePath());
            }
            File upload = new File(path.getAbsolutePath(), "static/pdf/upload");
            if (!upload.exists()) {
                boolean mkdirs = upload.mkdirs();
                String text = "测试";
                FileOutputStream fos = new FileOutputStream(upload.getAbsolutePath() +File.separator+ "drj.txt");
                fos.write(text.getBytes());
                fos.close();
//                System.err.println("不存在" + mkdirs);
            } else {
//                System.err.println(upload.getAbsolutePath());
//                System.err.println("存在");
            }
            File pdfFile = new File(upload.getAbsolutePath(),fileDirectory);
            InputStream inputStream = new FileInputStream(pdfFile);
            //输出文件
            InputStream fis = new BufferedInputStream(inputStream);
            buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            String json = new String(Base64.getEncoder().encode(buffer));
            return ResultJson.success(json);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResultJson.fail("文件不存在或者文件不可读或者文件是目录");
        }catch (IOException e){
            e.printStackTrace();
            return ResultJson.fail("文件流IO错误");
        }
    }

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