簡體   English   中英

如何獲取WebContent / WEB-INF / classes目錄的路徑

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM