0

I have files in a package in a javaproject, i want to iterate all the files are inside. Actually, I wrote an array of string manually in the code, with names of files. How can i do that array dynamically ?

enter image description here

Kitson
  • 1,650
  • 1
  • 18
  • 36
Flozza
  • 131
  • 2
  • 12

1 Answers1

0

There are several ways to do it. I recommend this approach:

Write a unit tests which lists all the files in the directory on the disk and compares the list with the array of strings in the code. If it finds a mismatch, it should print the correct code on the console and fail.

That way, the test will make sure that the list of files is correct. If it's no longer correct, a simple cut&paste will fix it.

The other approach would be to examine the classloader, try to create URLs and iterate over files in a package. Such code is brittle, tends to fail in surprising ways when running the app on a web server or with a different Java implementation. Don't go there.

Another solution would be to put the files into a "config" folder during installation. Then you application could use the standard File API to list/locate them.

EDIT I stand corrected. You can enumerate the files in a package:

Enumeration<URL> urls = getClass().getClassLoader().getResources( "javaapplication4/myfiles" );

This should return three URLs for the example above.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Is there a way this array build himself dynamically ? i want to add files in the package without any needing of changing this code. Autoload so – Flozza May 02 '13 at 08:07