hsz hsz - 3 months ago 25
Java Question

FileUtils.listFiles() on resources directory

In my project I have a

resources
directory with a
my_directory
inside.
my_directory
contains text files.

I want to loop this directory with:

URL resource = Resources.class.getResource("/my_directory");
File directory = new File(resource.getPath());
Collection<File> files = FileUtils.listFiles(directory, new String[]{"txt"}, true);


files
collection contains all
.txt
files.

It works well if I run this project in debugger. However if I build project to
jar
file, it gives an error:

java.lang.IllegalArgumentException: Parameter 'directory' is not a directory


directory
file path is:

/home/hsz/.../lib/my_project.jar!/my_directory


How can I use Apache's
FileUtils
on resources directory ?

Answer

When the files / directories are bundled inside a .jar file, they are no longer be treated as File objects. They can be read by acquiring their inputstream like

InputStream input = getClass().getResourceAsStream("my_directory/file");

I would suggest you to keep the folder with files in the filesystem and make the operations you want to perform. Is there any reason, you want to bundle them into a jar prior to these manipulation.

As per the answer in the below question, In Java 7, you can create a FileSystem from the JAR (zip) file, and then use NIO's directory walking and filtering mechanisms to search through it. This would make it easier to write code that handles JARs and "exploded" directories. You can try that!