问题 使用Java访问类路径中特定文件夹中的文件


我想在com.example.resources包中读取一堆文本文件。我可以使用以下代码读取单个文件:

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 
}

5947
2017-12-12 20:48


起源

我想访问类路径中的文件而不是像C:\\ resources这样的特定文件夹。 - Akadisoft
也许你想要这个: stackoverflow.com/questions/3923129/... - nwaltham
你可以为此重用代码(经过小的修改) stackoverflow.com/questions/176527/... - CAMOBAP


答案:


如果您将目录传递给 getResourceAsStream 然后它将返回目录中的文件列表(或至少它的流)。

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

我故意使用Thread获取资源,因为它将确保我获得父类加载器。这在Java EE环境中很重要,但对您的情况可能不是太多。


9
2017-12-12 21:06



嗨,我正在尝试使用你的答案。你能帮我解决这个问题: stackoverflow.com/questions/29430113/... ? - tch


这个SO线程 详细讨论这种技术。下面是一个有用的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);
  }

3
2017-12-12 21:00





我想那就是你想要的:

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
2017-12-12 20:52



你打算如何获得 File 包名称中的对象 String? - CAMOBAP
我试过了 File folder = new File("/com/example/resources") 它正在抛出NullPointerException - Akadisoft
编辑和工作 - Anton Hell