![](/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.