System.getProperty()方法获取系统属性的值(获取springboot项目下resource目录下的文件)

本来要上传文件到项目的resources文件夹中,如何获取项目的绝对路径?

于是乎查到了这个

String basePath = System.getProperty("user.dir");

图片来源:https://blog.csdn.net/weixin_37139197

获取springboot项目下resource目录下的文件方法:

File file = null;
try {
    file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/1.gif");     
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

但是打jar包后就无法获取,jar在文件系统中不是文件夹,其内部内容不能使用路径访问,改为流访问:

InputStream is = this.getClass().getResourceAsStream("/static/1.gif");

根据业务要求判断流是否使用,而我在项目中要使用文件,所以要将流转化为文件。

附一个简单的转化方法,逻辑有了,自行优化:

public static void inputStream2File(InputStream is, File file) throws Exception {
    OutputStream os = new FileOutputStream(file);
    int bytesRead = 0;
    byte[] buffer = new byte[2048];
    while ((bytesRead = is.read(buffer, 0, 2048)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
    os.close();
    is.close();
}
发布了73 篇原创文章 · 获赞 44 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_34928194/article/details/90269672