Java web專案如何獲取某個資料夾下面的檔案路徑 絕對路徑 ?
阿新 • • 發佈:2019-01-05
/**
* @param relativePath : 相對classpath路徑
*/
public static File getAbsoluteFileInWebContainer(String relativePath) {
File srcFile;
// classpath : {somedirectory}/target/classes/
String os = System.getProperty("os.name");
String classpath = null;
if (os.toLowerCase().startsWith("win" )) { // windows
classpath = ConcreteFileUtil.class.getResource("/").getPath().replaceFirst("/", "");
} else { // other
classpath = ConcreteFileUtil.class.getResource("/").getPath();
}
if (!(srcFile = new File(classpath.concat(relativePath))).exists()) {
srcFile = new File(classpath.replaceAll("WEB-INF/classes", "").concat(relativePath));
}
return srcFile.exists() ? srcFile : null;
}
Example:
ConcreteFileUtil.getAbsoluteFileInWebContainer("dict/figures/three-kingdoms-figures.dict"));