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

posted @ 2019-05-17 17:09  又尘埃  阅读(13813)  评论(1编辑  收藏  举报