一、Class.getResource()
Class.getResource()方法可以獲取相對於當前Class所在目錄的資源路徑。
String path = MyClass.class.getResource("file.txt").getPath(); System.out.println(path);
上述代碼可以獲取到file.txt文件相對於MyClass.class所在目錄的路徑。
需要注意的是,getResource()方法返回的是URL對象,需要調用getPath()方法獲取文件路徑。
二、ClassLoader.getResource()
ClassLoader.getResource()方法可以獲取classpath下的資源路徑。
URL url = MyClass.class.getClassLoader().getResource("file.txt"); String path = url.getPath(); System.out.println(path);
上述代碼獲取classpath下的file.txt文件路徑。
三、File對象獲取路徑
通過File對象獲取路徑需要注意路徑的寫法。
File file = new File("src/main/resources/file.txt"); String path = file.getAbsolutePath(); System.out.println(path);
該方法需要寫絕對路徑或者相對於當前程序所在的工作目錄的相對路徑。
四、Properties文件讀取
在Java程序中,經常需要通過properties文件獲取配置信息。
Properties props = new Properties(); InputStream in = MyClass.class.getClassLoader().getResourceAsStream("config.properties"); props.load(in); String value = props.getProperty("key"); System.out.println(value);
上述代碼通過getResourceAsStream()方法獲取classpath下的config.properties文件的輸入流,然後通過Properties類的getProperty()方法獲取對應的value值。
五、Spring統一資源載入
Spring框架提供了一種統一的方式載入Classpath,文件系統,URL和ServletContext等資源。
Resource resource = new ClassPathResource("file.txt"); String path = resource.getFile().getAbsolutePath(); System.out.println(path);
上述代碼通過ClassPathResource類獲取classpath下的file.txt文件的路徑。
原創文章,作者:YUQUY,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/335032.html