Java—获取文件路径的几种方式以及解决文件名中文乱码


#一、获取文件路径 ##方式一: 获取当前工程resources目录下文件的路径

String fileName = this.getClass().getClassLoader().getResource("文件名").getPath(); //获取文件路径

运行结果:

/D:/work/svnCode/RYZS-Automation/target/classes/5个身份证号.csv

##方法二: 获取当前类所在工程的路径

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

运行结果:

D:\work\svnCode\RYZS-Automation

##方式三: 获取当前类所在工程的路径

File directory = new File("");//参数为空
String courseFile = directory.getCanonicalPath() ;
String author =directory.getAbsolutePath();

运行结果:

D:\work\svnCode\RYZS-Automation
D:\work\svnCode\RYZS-Automation

##方式四:

  1. 获取当前类的所在工程路径:
File f = new File(this.getClass().getResource("/").getPath()); 

结果:

D:\work\svnCode\RYZS-Automation\target\classes
  1. 如果不加“/” ,获取当前类的绝对路径:
File f = new File(this.getClass().getResource("").getPath()); 

结果:

D:\work\svnCode\RYZS-Automation\target\classes\com\chinal\ryzsAutomation\service

#二、获取的路径中文件名中文乱码

        String localFilePath = this.getClass().getClassLoader().getResource("5个身份证号.csv").getPath();
        try {
            localFilePath = URLDecoder.decode(localFilePath, "UTF-8");
            System.out.println(localFilePath);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

Reference https://blog.csdn.net/dream_broken/article/details/31762807 https://blog.csdn.net/oschina_40188932/article/details/78833754


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM