2012-12-12 27 views
11

Tôi muốn đọc một loạt tệp văn bản trong gói com.example.resources. Tôi có thể đọc một tập tin duy nhất sử dụng đoạn mã sau:Truy cập tệp trong thư mục cụ thể trong đường dẫn lớp bằng cách sử dụng Java

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

Có cách nào để có được danh sách các tập tin và sau đó vượt qua từng yếu tố để getResourceAsStream?

EDIT: On gợi ý ramsinb tôi đã thay đổi mã của tôi như sau:

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

Tôi muốn truy cập tệp trong classpath chứ không phải từ một thư mục cụ thể như tài nguyên C: \\. – Akadisoft

+1

Có lẽ bạn muốn điều này: http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory – nwaltham

+0

Bạn có thể sử dụng lại mã này (sau khi sửa đổi nhỏ) http: // stackoverflow .com/questions/176527/how-can-i-enumerate-all-classes-in-a-package-và-them-them-to-a-list – CAMOBAP

Trả lời

9

Nếu bạn chuyển vào danh sách các tệp trong thư mục (hoặc ít nhất một luồng của tệp).

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

Tôi cố ý sử dụng Chủ đề để lấy tài nguyên vì nó sẽ đảm bảo tôi có trình tải lớp cấp độ gốc. Điều này quan trọng trong môi trường Java EE tuy nhiên có lẽ không quá nhiều cho trường hợp của bạn.

+0

Xin chào, tôi đang cố gắng sử dụng câu trả lời của bạn. Bạn có thể giúp tôi với điều đó không: http://stackoverflow.com/questions/29430113/accessing-files-in-specific-folder-in-classpath-using-java-works-only-for-sing? – tch

0

Tôi nghĩ rằng thats những gì bạn muốn:

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

Làm thế nào để bạn có kế hoạch lấy đối tượng 'File' từ tên gói' Chuỗi'? – CAMOBAP

+0

Tôi đã thử 'Thư mục tệp = tệp mới ("/com/example/resources ")' và nó đang ném NullPointerException – Akadisoft

+0

đã chỉnh sửa và làm việc –

3

This SO thread thảo luận về kỹ thuật này một cách chi tiết. Dưới đây là một phương thức Java hữu ích liệt kê các tệp từ một thư mục tài nguyên đã cho.

/** 
    * 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); 
    } 
Các vấn đề liên quan