java获取指定资源文件路径的几种方法

时间:2020-01-29 21:14:48 类型:JAVA
字号:    

指定资源路径的方法有两种:

一种是绝对路径,一种是相对路径。

获取当前类的所在工程路径; 
File f = new File(this.getClass().getResource("/").getPath()); 
System.out.println(f); 
获取当前类的绝对路径; 
File f = new File(this.getClass().getResource("").getPath()); 
System.out.println(f); 
获取当前类的所在工程路径; 
File directory = new File("");//参数为空 
String courseFile = directory.getCanonicalPath() ; 
System.out.println(courseFile); 
获取当前工程src目录下selected.txt文件的路径:
URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt"); 
System.out.println(xmlpath);


<