簡體   English   中英

錯誤地訪問資源文件

[英]Accessing resource file incorrectly

我正在嘗試使用以下代碼段訪問Eclipse中的資源文件。

public class ResourceHandler {

    public void test() throws IOException {
        String filePath = this.getClass().getResource("resources/MANIFEST_HAPPYVERSION.MF").getPath();// throws a NPE
        System.out.println( filePath );
        //System.out.println( file.exists() );
    }

    public static void main(String [] args) throws Exception {
        ResourceHandler test = new ResourceHandler();
       test.test();
    }
}

這是我的目錄結構的照片。 目錄結構

我到底在做什么錯?

正確的方法是使用Classloader中的getResource。 因此它可以在任何地方使用,包括Web容器。

URL resource = this.getClass().getClassLoader().getResource("MANIFEST_HAPPYVERSION.MF");
if (resource != null) {
    String path = resource.getPath(); // You can try getFile...
}

暫無
暫無

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

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