1、利用System.getProperty()函數獲取當前路徑:
System.out.println(System.getProperty("user.dir"));//user.dir指定了當前的路徑2、使用File提供的函數獲取當前路徑:
File directory = new File("");//設定為當前文件夾
System.out.println(directory.getCanonicalPath());//獲取標準的路徑
System.out.println(directory.getAbsolutePath());//獲取絕對路徑
File.getCanonicalPath()和File.getAbsolutePath()大約只是對于new File(".")和new File("..")兩種路徑有所區別。
對于getCanonicalPath()函數,“."就表示當前的文件夾,而”..“則表示當前文件夾的上一級文件夾
對于getAbsolutePath()函數,則不管”.”、“..”,返回當前的路徑加上你在new File()時設定的路徑
至于getPath()函數,得到的只是你在new File()時設定的路徑
比如當前的路徑為 C:\test :
File directory = new File("abc");
directory.getCanonicalPath(); //得到的是C:\test\abc
directory.getAbsolutePath(); //得到的是C:\test\abc
direcotry.getPath(); //得到的是abc
File directory = new File(".");
directory.getCanonicalPath(); //得到的是C:\test
directory.getAbsolutePath(); //得到的是C:\test\.
direcotry.getPath(); //得到的是.
File directory = new File("..");
directory.getCanonicalPath(); //得到的是C:\
directory.getAbsolutePath(); //得到的是C:\test\..
direcotry.getPath(); //得到的是..
源碼如下:public class ReadPropertiesUtil {
/**
* @param args
*/
public static void main(String[] args) {
File directory = new File("");//設定為當前文件夾
System.out.println(directory.getAbsolutePath());//獲取絕對路徑
System.out.println(directory.getPath()); //獲得new File()時設定的路徑
System.out.println(System.getProperties());
/**
* class.getClassLoader().getResourceAsStream($path), 其中$path默認是src源路徑,maven項目一般配置了多個源路徑
* 例如:maven項目的源路徑為:src/main/java,src/main/resources,src/test/java,src/test/resources,在此四個源
* 路徑下的文件可以直接寫文件名即可讀取
*/
System.out.println(Thread.currentThread().getContextClassLoader().getResource("com/wpy/json/data.properties"));
System.out.println(Thread.currentThread().getContextClassLoader().getResource("db.properties"));
System.out.println(Thread.currentThread().getContextClassLoader().getResource("src/test/java/file1.properties"));
System.out.println(Thread.currentThread().getContextClassLoader().getResource("file2.properties"));
System.out.println(Thread.currentThread().getContextClassLoader().getResource("file3.properties"));
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
System.out.println(classloader);
if (classloader == null) {
Properties iframeproperties = new Properties();
classloader = iframeproperties.getClass().getClassLoader();
}
System.out.println(classloader);
try {
System.out.println(directory.getCanonicalPath());//獲取標準的路徑
} catch (IOException e) {
e.printStackTrace();
}
}