hsz hsz - 1 year ago 262
Java Question

FileUtils.listFiles() on resources directory

In my project I have a

directory with a
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);

collection contains all

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

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

file path is:


How can I use Apache's
on resources directory ?

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download