![](/img/trans.png)
[英]How to write to a file in WebContent directory from a class in WEB-INF/classes directory
[英]How to get path to WebContent/WEB-INF/classes directory
我有以下代碼:
final String MY_DIR_PATH = "myDir/";
URL destDirUrl = getClass().getClassLoader().getResource(MY_DIR_PATH);
if (destDirUrl == null) {
// what should go here?
}
Path destDirPath = Paths.get(destDirUrl.toURI());
if (Files.notExists(destDirPath)) {
LOGGER.info("New directory \"" + destDirPath + "\" will be created.");
Files.createDirectories(destDirPath);
}
如果存在myDir
,則在調試后第二行中的desDirUrl
包含:
file:/D:/myDevelopment/MyProject/WebContent/WEB-INF/classes/myDir/
但是,現在我必須對此進行增強,以處理以下情況:如果myDir
不存在, myDir
在以下file:/D:/myDevelopment/MyProject/WebContent/WEB-INF/classes/
創建myDir
file:/D:/myDevelopment/MyProject/WebContent/WEB-INF/classes/
path。
我不知道在if
放入什么,這樣我就可以在下一行獲得相同的URL
以獲得destDirPath
。
我試過了,
URL classURL = getClass().getProtectionDomain().getCodeSource().getLocation();
但這返回URL
為:
file:/D:/myDevelopment/MyProject/java/bin/
這是不正確的。
我如何:
1)首先檢索file:/D:/myDevelopment/MyProject/WebContent/WEB-INF/classes
作為URL
。
2)然后如何向其中添加/myDir
,以便下一行Path destDirPath = Paths.get(destDirUrl.toURI());
像以前一樣工作。
更新:
我也嘗試過:
URL classURL = getClass().getClassLoader().getResource(".");
和
URL classURL = getClass().getClassLoader().getResource("/");
和
URL classURL = getClass().getClassLoader().getResource("");
但沒有一個工作。
我會嘗試這樣的事情:
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
try {
URI uri = new URI(url.toString() + "/myDir");
Path path = Paths.get(uri);
if(!Files.exists(path)){
Files.createDirectory(path);
}
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.