2016-05-05 54 views
0

我試圖編寫一個Java 1.7應用程序,可以從命令行傳遞任意文件。該文件將被添加到ClassLoader中,以便它可以被用作資源。使用文件作爲URLClassLoader的資源

將該文件添加到URLClassLoader似乎可行,但是如何在添加到ClassLoader後將該文件作爲資源獲取?

import java.io.File; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLClassLoader; 
import java.util.Arrays; 

public class ClassLoaderTest { 

    public static void main(String... args) throws MalformedURLException { 

    File file = new File("/tmp/application.conf"); 
    URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()}); 
    System.out.println("ClassLoader URLs: " + Arrays.toString(classLoader.getURLs())); 

    if (file.exists()) { 
     System.out.println("File \"" + file.getAbsolutePath() + "\" exists!"); 
    } else { 
     System.out.println("File \"" + file.getAbsolutePath() + "\" does not exist!"); 
     return; 
    } 

    URL url = classLoader.getResource(file.getAbsolutePath()); 

    System.out.println("File \"" + file.getAbsolutePath() + "\" as url: " + url); 

    assert url != null; 

    } 
} 
+0

爲什麼你需要使用ClassLoader?當資源與已知類位於同一目錄中時,這很有用,但如果您只是想打開文件並使用它,則不需要使用除URL和文件以外的其他任何內容。 –

+0

@PaulHicks這將被集成到期望從初始化時提供的ClassLoader中檢索資源。 –

+1

我注意到你的文件不是jar。 'URLClassLoader'只能用於罐子和罐子目錄。您可以將您的conf文件放入jar中,也可以實現自己的類加載器。 –

回答

2

URLClassLoader僅支持jar文件和文件目錄。所以有兩種選擇:

  1. 把你的資源放到一個jar文件中,然後把那個jar文件加入你的URLClassLoader
  2. 將目錄提供給類加載器,並使用該目錄中文件的相對路徑。
+0

並使用以JAR根爲根的路徑,而不是絕對路徑名。 '只有JAR文件和JAR文件的目錄'不正確。如果你命名一個目錄,它會在目錄和包結構重合的情況下找到它內部或下面的.class文件和資源。 – EJP

+0

添加目錄,然後通過文件名得到資源完美地工作。謝謝你的幫助。 –