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