简体   繁体   English

Java中的listFiles()方法在.jar中不起作用

[英]listFiles() method in Java doesn't work in .jar

I have a "Pictures" folder in my project like this: link 我的项目中有一个“图片”文件夹,如下所示: 链接

I want to find the number of files in some of these folders. 我想找到其中一些文件夹中的文件数。

I'm using: int length = new File("./Pictures/1").listFiles().length which works perfectly fine when I run the IDE. 我正在使用: int length = new File("./Pictures/1").listFiles().length在运行IDE时可以很好地工作。 However when I convert my project to .jar File I get a NullPointerException. 但是,当我将项目转换为.jar文件时,会收到NullPointerException.

A jar file is basically a zip file. jar文件基本上是一个zip文件。 Your code would be looking for the Pictures directory on your file system, not inside the jar file. 您的代码将在文件系统上而不是jar文件中查找Pictures目录。 To access files inside a jar file (also works outside of jar, it searches from the classpath) you can use Class.getResource() (and getResourceAsStream() ). 要访问jar文件中的文件(也可以在jar之外工作,它从类路径搜索),可以使用Class.getResource() (和getResourceAsStream() )。

However I'm not certain whether it's possible to use those for file listings as you want, they're mostly used for retrieving single resources from the classpath. 但是我不确定是否可以根据需要将它们用于文件列表,它们主要用于从类路径中检索单个资源。

You cannot use File with jar entries. 您不能将File与jar条目一起使用。 You must locate the jar file and treat it as a zip file. 您必须找到jar文件并将其视为zip文件。

You use relative paths to folders and when you run from IDE relative paths work correctly since they are relative to project root directory. 您可以使用文件夹的相对路径,并且从IDE运行时,相对路径可以正常工作,因为它们是相对于项目根目录的。 But when you run jar JVM assumes that relative paths are relative to the directory where jar is located. 但是,当您运行jar时,JVM会假定相对路径是相对于jar所在目录的。

If you just want to check how File.listFiles() work then you can use full path to that folder. 如果只想检查File.listFiles()工作方式,则可以使用该文件夹的完整路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM