2012-12-12 81 views
11

我想讀取com.example.resources包中的一堆文本文件。使用Java在類路徑中訪問特定文件夾中的文件

InputStream is = MyObject.class.getResourceAsStream("resources/file1.txt") 
InputStreamReader sReader = new InputStreamReader(is); 
BefferedReader bReader = new BufferedReader(sReader); 
... 

是否有一種方式來獲得文件的列表,然後將每個元素傳遞給getResourceAsStream:我可以使用下面的代碼讀取一個文件?

編輯: 在ramsinb建議我改變了我的代碼如下:

BufferedReader br = new BufferedReader(new InputStreamReader(MyObject.class.getResourceAsStream("resources"))); 
String fileName; 
while((fileName = br.readLine()) != null){ 
    // access fileName 
} 
+2

我想訪問類路徑中的文件,而不是像C:\\ resources這樣的特定文件夾。 – Akadisoft

+1

也許你想要這個:http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory – nwaltham

+0

你可以重用代碼(經過小的修改)http:// stackoverflow .com/questions/176527/how-can-i-enumerate-all-classes-in-a-package-and-add-them-to-a-list – CAMOBAP

回答

9

如果你在一個目錄傳遞給getResourceAsStream方法那麼它將返回文件的列表中的目錄(或至少流的話)。

Thread.currentThread().getContextClassLoader().getResourceAsStream(...) 

我故意使用線程獲取資源,因爲它會確保我得到父類加載器。這在Java EE環境中很重要,但對於您的情況可能不會太多。

+0

嗨,我試圖用你的答案。你能幫我一下:http://stackoverflow.com/questions/29430113/accessing-files-in-specific-folder-in-classpath-using-java-works-only-for-sing? – tch

0

我想這就是你想要的東西:

String currentDir = new java.io.File(".").toURI().toString(); 
// AClass = A class in this package 
String pathToClass = AClass.class.getResource("/packagename).toString(); 
String packagePath = (pathToClass.substring(currentDir.length() - 2)); 

String file; 
File folder = new File(packagePath); 
File[] filesList= folder.listFiles(); 

for (int i = 0; i < filesList.length; i++) 
{ 
    if (filesList[i].isFile()) 
    { 
    file = filesList[i].getName(); 
    if (file.endsWith(".txt") || file.endsWith(".TXT")) 
    { 
     // DO YOUR THING WITH file 
    } 
    } 
} 
+0

你如何計劃從包名獲得'File'對象' String'? – CAMOBAP

+0

我試過'文件夾=新文件(「/ com/example/resources」)'這是拋出NullPointerException – Akadisoft

+0

編輯和工作 –

3

This SO thread詳細討論了這種技術。以下是列出給定資源文件夾中的文件的有用Java方法。

/** 
    * List directory contents for a resource folder. Not recursive. 
    * This is basically a brute-force implementation. 
    * Works for regular files and also JARs. 
    * 
    * @author Greg Briggs 
    * @param clazz Any java class that lives in the same place as the resources you want. 
    * @param path Should end with "/", but not start with one. 
    * @return Just the name of each member item, not the full paths. 
    * @throws URISyntaxException 
    * @throws IOException 
    */ 
    String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException { 
     URL dirURL = clazz.getClassLoader().getResource(path); 
     if (dirURL != null && dirURL.getProtocol().equals("file")) { 
     /* A file path: easy enough */ 
     return new File(dirURL.toURI()).list(); 
     } 

     if (dirURL == null) { 
     /* 
     * In case of a jar file, we can't actually find a directory. 
     * Have to assume the same jar as clazz. 
     */ 
     String me = clazz.getName().replace(".", "/")+".class"; 
     dirURL = clazz.getClassLoader().getResource(me); 
     } 

     if (dirURL.getProtocol().equals("jar")) { 
     /* A JAR path */ 
     String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file 
     JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); 
     Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar 
     Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory 
     while(entries.hasMoreElements()) { 
      String name = entries.nextElement().getName(); 
      if (name.startsWith(path)) { //filter according to the path 
      String entry = name.substring(path.length()); 
      int checkSubdir = entry.indexOf("/"); 
      if (checkSubdir >= 0) { 
       // if it is a subdirectory, we just return the directory name 
       entry = entry.substring(0, checkSubdir); 
      } 
      result.add(entry); 
      } 
     } 
     return result.toArray(new String[result.size()]); 
     } 

     throw new UnsupportedOperationException("Cannot list files for URL "+dirURL); 
    } 
相關問題