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

1、使用類(lèi)加載器獲取資源文件路徑
2、使用ClassPathResource獲取資源文件路徑
3、使用FileSystemResource獲取資源文件路徑
4、使用URL獲取資源文件路徑
5、使用相對(duì)路徑獲取資源文件路徑
下面分別詳細(xì)介紹這幾種方法。
1、使用類(lèi)加載器獲取資源文件路徑
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、使用相對(duì)路徑獲取資源文件路徑
public String getResourcePathByRelativePath() {
return getClass().getClassLoader().getResource("test.txt").getPath();
}
以上就是Java中獲取resource文件路徑的幾種方法,在實(shí)際開(kāi)發(fā)中,可以根據(jù)需要選擇合適的方法來(lái)獲取資源文件路徑,需要注意的是,這些方法都是基于類(lèi)加載器的,所以在使用時(shí)需要確保資源文件已經(jīng)被加載到類(lèi)加載器中,如果資源文件沒(méi)有被加載,那么這些方法將返回null。
網(wǎng)頁(yè)標(biāo)題:java獲取resource目錄路徑
標(biāo)題URL:http://fisionsoft.com.cn/article/cdppeci.html


咨詢
建站咨詢
