2015-11-15 19 views
2

我想創建一個文件夾內搜索.png文件並返回一個字符串數組與每個文件的相應路徑的方法。它必須查看資源文件夾放置在不在src中,但在項目中。如何創建一個String數組,其元素是位於資源文件夾中的所有png文件?

// Analyzes specified folder and returns a file array 
// populated with the .png files found in that folder 
private File[] imageReader(String filePath) { 
    File folder = new File(filePath); 
    return folder.listFiles (new FilenameFilter() { 
     public boolean accept(File filePath, String filename) 
     { return filename.endsWith(".png"); } 
    }); 
} 

// Converts the file array into a string array 
private String[] listPngFiles(String filePath) { 
    File[] imagesFileArray = imageReader(filePath); // file array 
    String[] imagesStringArray = new String[imagesFileArray.length]; 

    for(int i=0; i<imagesFileArray.length; i++) { 
     imagesStringArray[i] = "" + imagesFileArray[i]; 
     imagesStringArray[i] = imagesStringArray[i].substring(6); // discards "/images" from directory string 
    } 

    return imagesStringArray; 
} 

然而,當我運行導出的可執行的JAR文件不工作:在Eclipse中運行時, 下面的代碼工作。這是我目前的項目設置:

project setup

我曾嘗試下面的代碼,但它沒有工作,要麼:

ClassLoader classLoader = getClass().getClassLoader(); 
File folder = new File(classLoader.getResource(filePath).getFile()); 

的原因,我這樣做是因爲我想有一個JButton顯示來自內部的子文件夾中的一個選擇一個圖標圖像資源文件夾。我的JButton已經有以下代碼:

.setIcon(new ImageIcon(GameLogic.class.getResource(**insert listPngFiles array element here**))); 

您對此事的幫助將不勝感激。

+0

豈不只是簡單的把所有的圖像的名字在一些ini文件中的資源文件夾,然後打開並閱讀該文件當你啓動應用程序?資源不會經常更改,因此沒有理由在動態讀取中執行此操作。 – RealSkeptic

回答

相關問題