簡體   English   中英

如何測試Eclipse捆綁包中的URL是否為目錄?

[英]How to test if a URL from an Eclipse bundle is a directory?

我正在嘗試從插件中內置的捆綁包的內容填充目錄。 以下代碼在捆綁軟件為文件系統時有效,但在捆綁軟件為JAR時失敗。

測試URL是否為目錄的最佳方法是什么? 還是有一種完全不同的,更好的方法從資源束創建文件結構?

    static private void bundleCopy(String dir, String destination) throws IOException {
    Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();

    for (@SuppressWarnings("unchecked")
        Enumeration<URL> en = (Enumeration<URL>) bundle.findEntries(dir, "*", true); 
            en.hasMoreElements();) {
        URL url = en.nextElement();
        String toFileName = destination + url.getPath().substring(dir.length());
        File toFile = new File(toFileName);
        InputStream in;

        try {
            in = url.openStream();
        } catch (FileNotFoundException e) {
            // this exception get thrown for file system directories but not for jar file ones
            if (!toFile.mkdir()) {
                throw new IOException("bundleCopy: " + "directory Creation Failed: "
                        + toFileName);
            }
            continue;
        }
        FileCopy.coreStreamCopy(in, toFile);
    }
}

我找到了答案:

關鍵是目錄的Enumeration條目以'/'結尾。

以下內容可以正確區分JAR和文件系統的目錄和文件:

    static private void bundleCopy(String dir, String destination) 
    throws IOException, URISyntaxException {

    Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();
    Enumeration<URL> en = bundle.findEntries(dir, "*", true);
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        String pathFromBase = url.getPath().substring(dir.length()+1);
        String toFileName = destination + pathFromBase;
        File toFile = new File(toFileName);

        if (pathFromBase.lastIndexOf('/') == pathFromBase.length() - 1) {
            // This is a directory - create it and recurse
            if (!toFile.mkdir()) {
                throw new IOException("bundleCopy: " + "directory Creation Failed: " + toFileName);
            }
        } else {
            // This is a file - copy it
            FileCopy.coreStreamCopy(url.openStream(), toFile);
        }        
    }
}

您可以嘗試使用諸如new File(FileLocator.resolve(url).toUri()) ,使用本機Java協議將Eclipse特定的URL轉換為URL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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