新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
java獲取resource目錄路徑
在Java中,獲取resource文件路徑的方法有以下幾種:

1、使用類加載器獲取資源文件路徑
2、使用ClassPathResource獲取資源文件路徑
3、使用FileSystemResource獲取資源文件路徑
4、使用URL獲取資源文件路徑
5、使用相對路徑獲取資源文件路徑
下面分別詳細(xì)介紹這幾種方法。
1、使用類加載器獲取資源文件路徑
public String getResourcePathByClassLoader() {
ClassLoader classLoader = getClass().getClassLoader();
URL resourceUrl = classLoader.getResource("test.txt");
return resourceUrl.getPath();
}
2、使用ClassPathResource獲取資源文件路徑
import org.springframework.core.io.ClassPathResource;
public String getResourcePathByClassPathResource() {
ClassPathResource classPathResource = new ClassPathResource("test.txt");
return classPathResource.getFile().getAbsolutePath();
}
3、使用FileSystemResource獲取資源文件路徑
import org.springframework.core.io.FileSystemResource;
import java.io.File;
public String getResourcePathByFileSystemResource() {
FileSystemResource fileSystemResource = new FileSystemResource(new File("test.txt"));
return fileSystemResource.getFile().getAbsolutePath();
}
4、使用URL獲取資源文件路徑
public String getResourcePathByURL() throws MalformedURLException {
URL resourceUrl = getClass().getClassLoader().getResource("test.txt");
return resourceUrl.getPath();
}
5、使用相對路徑獲取資源文件路徑
public String getResourcePathByRelativePath() {
return getClass().getClassLoader().getResource("test.txt").getPath();
}
以上就是Java中獲取resource文件路徑的幾種方法,在實際開發(fā)中,可以根據(jù)需要選擇合適的方法來獲取資源文件路徑,需要注意的是,這些方法都是基于類加載器的,所以在使用時需要確保資源文件已經(jīng)被加載到類加載器中,如果資源文件沒有被加載,那么這些方法將返回null。
標(biāo)題名稱:java獲取resource目錄路徑
本文網(wǎng)址:http://m.5511xx.com/article/cdppeci.html


咨詢
建站咨詢
