#一、獲取文件路徑 ##方式一: 獲取當前工程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
##方式四:
- 獲取當前類的所在工程路徑:
File f = new File(this.getClass().getResource("/").getPath());
結果:
D:\work\svnCode\RYZS-Automation\target\classes
- 如果不加“/” ,獲取當前類的絕對路徑:
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