广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java如何获取resources下的文件路径和创建临时文件
  • 146
分享到

Java如何获取resources下的文件路径和创建临时文件

JavaresourcesJava获取文件路径Java创建临时文件 2022-12-29 15:12:30 146人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录获取resources下的文件路径和创建临时文件获取resources下的文件路径resources下创建临时文件Java获取文件路径及路径乱码问题java获取项目路径中文乱码总

获取resources下的文件路径和创建临时文件

之前处理根据模板文件,批量导入xxx.zip 的下载功能,用到这两个知识,就简单记录下,对于流的处理就跳过了      

由于Maven项目打包会把 src/main/java 和 src/main/resources 下的文件放到 target/classes 下,所以统一以根路径代表此目录。

创建一个SpringBoot项目

      

server:
  port: 80
  servlet:
    context-path: /JQ_Resource

获取resources下的文件路径

总结起来有两点:

1、Class.getResource()的获取资源路径

  • 如果以 / 开头,则从根路径开始搜索资源。
  • 如果不以 / 开头,则从当前类所在的路径开始搜索资源。

2、ClassLoader.getResource()的资源获取不能以 / 开头,统一从根路径开始搜索资源。

String path = this.getClass().getClassLoader().getResource("xxx").getPath();

测试:

    public void getResource() {
        //1、通过Class的getResource方法
        String a1 = RescourceController.class.getResource("/cn/jq/jqresource/pojo/User.class").getPath();
        String a2 = this.getClass().getResource("../pojo/User.class").getPath();
        String a3 = RescourceController.class.getResource("/static/a.txt").getPath();
        String a4 = this.getClass().getResource("../../../../static/a.txt").getPath();
        System.out.println(a1.equals(a2)); // true
        System.out.println(a4); // /D:/JQ/workspace/JQ_Resource/target/classes/static/a.txt
 
        // 2、通过本类的ClassLoader的getResource方法
        String b1 = RescourceController.class.getClassLoader().getResource("cn/jq/jqresource/pojo/User.class").getPath();
        String b2 = this.getClass().getClassLoader().getResource("static/a.txt").getPath();
        String b3 = this.getClass().getClassLoader().getResource("static/resource/jq.docx").getPath();
 
        // 3、通过ClassLoader的getSystemResource方法
        String c1 = ClassLoader.getSystemClassLoader().getResource("cn/jq/jqresource/pojo/User.class").getPath();
        String c2 = ClassLoader.getSystemClassLoader().getResource("static/a.txt").getPath();
        String c3 = ClassLoader.getSystemClassLoader().getResource("static/resource/jq.docx").getPath();
 
        // 4、通过ClassLoader的getSystemResource方法
        String d1 = ClassLoader.getSystemResource("cn/jq/jqresource/pojo/User.class").getPath();
        String d2 = ClassLoader.getSystemResource("static/a.txt").getPath();
        String d3 = ClassLoader.getSystemResource("static/resource/jq.docx").getPath();
 
        // 5、通过Thread方式的ClassLoader的getResource方法
        String e1 = Thread.currentThread().getContextClassLoader().getResource("cn/jq/jqresource/pojo/User.class").getPath();
        String e2 = Thread.currentThread().getContextClassLoader().getResource("static/a.txt").getPath();
        String e3 = Thread.currentThread().getContextClassLoader().getResource("static/resource/jq.docx").getPath();
    }

resources下创建临时文件

    public void createFile(httpservletRequest request) throws ioException {
        String contextPath = request.getContextPath(); // /JQ_Resource
 
        String filePath = contextPath + "/temp/hr.zip";
        String dirPath = contextPath + "/temp/hr";
        File file = new File(filePath);
        File dir = new File(dirPath);
        if (file.exists()) {
            // 删除指定文件,不存在报异常
            FileUtils.forceDelete(file);
        }
        file.createNewFile();
 
 
        if (dir.isDirectory()) {
            // 清除该目录下的文件及子目录文件而不删除该目录文件夹。该目录不存在会报错
            FileUtils.cleanDirectory(dir);
        } else {
            dir.mkdirs();
        }
 
        File dir_File = new File(dirPath + "/" + "dir_file.txt");
 
        System.out.println(dir_File.getPath()); // \JQ_Resource\temp\hr\dir_file.txt
        System.out.println(file.exists()); // true
    }

Java获取文件路径及路径乱码问题

System.getProperty(“user.dir”)
  • 构造:File(path)
  • 构造:FileInputStream(“path”)
XXX.class.getResource("").getPath()

XXX.class.getClassLoader().getResource("").getPath()

(以下演示均为windows系统)

相对路径:src/test/resources/test.txt

绝对路径:D:\glearning\my_opensource\somproject\src\main\resources\test\test.txt

  • “.”符号:java文件所在的当前目录(编译后是.class文件所在的当前目录)
  • “…”符号:java文件所在的上一级目录(编译后.class文件的上一级目录)
  • “/”符号:以/开头的,在URL类中表示项目的根路径(maven编译后就是target目录的位置)。
System.getProperty(“user.dir”)

表示当前用户目录,即JVM调用目录

File(path)与FileInputStream(path)

java获取项目路径中文乱码

解决方法

import java.io.UnsupportedEncodingException;  
import java.net.URI;  
import java.net.URL;  
import java.net.URLDecoder;  
  
public class Test01 {  
  
    public static void main(String[] args) {  
        getPathMethod01();  
        getPathMethod02();  
        getPathMethod03();  
        getPathMethod04();  
    }  
    private static String getPathMethod01(){  
        String p = System.getProperty("user.dir");  
        System.out.println("方法一路径:"+p);  
        //方法一路径:E:\test\test04练  习
        return p;  
    }  
      
    private static String getPathMethod02(){  
        URL url= Test01.class.getResource("");  
        String p = url.getPath();  
        System.out.println("方法二路径:"+p);  
		//方法二路径:/E:/test/test04%e7%bb%83%20%20%e4%b9%a0/bin/com/fei/
        try {  
            System.out.println("方法二解码路径:"+URLDecoder.decode(p, "UTF-8"));  
			//方法二解码路径:/E:/test/test04练  习/bin/com/fei/
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return p;  
    }  
      
    private static String getPathMethod03(){  
        URL url= Test01.class.getResource("/");  
        String p = url.getPath();  
        System.out.println("方法三路径:"+p); 
		//方法三路径:/E:/test/test04%e7%bb%83%20%20%e4%b9%a0/bin/
        try {  
            System.out.println("方法三解码路径:"+URLDecoder.decode(p, "UTF-8"));  
			//方法三解码路径:/E:/test/test04练  习/bin/
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return p;  
    }  
    private static String getPathMethod04(){  
        try {  
            URI uri = Test01.class.getResource("/").toURI();  
            String p = uri.getPath();  
            System.out.println("方法四路径:"+p);  
			//方法四路径:/E:/test/test04练  习/bin/
            return p;  
        } catch (Exception e) {  
            e.printStackTrace();  
            throw new RuntimeException(e);  
        }  
    }  
}  

通过看代码和运行结果可以看到,用url.getPath()获取到的路径被utf-8编码了,用URLDecoder.decode(p, “UTF-8”)即可解码。

总结

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

--结束END--

本文标题: Java如何获取resources下的文件路径和创建临时文件

本文链接: https://www.lsjlt.com/news/176217.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作