2012-12-12 15 views
11

Desidero leggere un gruppo di file di testo nel pacchetto com.example.resources. Posso leggere un singolo file utilizzando il seguente codice:Accesso ai file in una cartella specifica in classpath utilizzando Java

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

C'è un modo per ottenere l'elenco di file e quindi passare ogni elemento a getResourceAsStream?

EDIT: Su suggerimento ramsinb ho cambiato il mio codice come segue:

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

Desidero accedere ai file in classpath e non da una cartella specifica come C: \\ resources. – Akadisoft

+1

Forse vuoi questo: http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory – nwaltham

+0

Puoi riutilizzare il codice per questo (dopo piccole modifiche) http: // StackOverflow .com/questions/176527/how-can-i-enumerate-all-classes-in-a-package-and-add-them-to-a-list – CAMOBAP

risposta

9

Se si passa in una directory al metodo getResourceAsStream allora verrà restituito un elenco dei file nella directory (o almeno un flusso di esso).

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

Ho utilizzato di proposito la discussione per ottenere la risorsa poiché garantirà di ottenere il caricatore della classe genitore. Questo è importante in un ambiente Java EE, ma probabilmente non troppo per il tuo caso.

+0

Ciao, sto cercando di usare la tua risposta. Potete aiutarmi in questo: http://stackoverflow.com/questions/29430113/accession-files-in-specific-folder-in-classpath-using-java-works-only-for-sing? – tch

0

Penso che è ciò che si desidera:

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

Come si pianifica di ottenere l'oggetto 'File' dal nome del pacchetto' STRING'? – CAMOBAP

+0

Ho provato 'File folder = new File ("/com/example/resources ")' e sta lanciando NullPointerException – Akadisoft

+0

modificato e funzionante –

3

This SO thread discutere di questa tecnica in dettaglio. Di seguito è riportato un utile metodo Java che elenca i file da una determinata cartella di risorse.

/** 
    * 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); 
    } 
Problemi correlati