tags:

views:

60

answers:

1

I am working on a small basic GUI program that gets the files from my resources and gets the names of the files and places them in a combo box. for example i just have a file inside the same package called images and trying to get the files names. the way I get the file is by using the getResoure() like so

java.net.URL url = FileDemo.class.getResource("images");

but when I try to get the files inside the directory

  File urlfile = new File(url.toString());

  String[] files = urlfile.list();

the first line will convert the url to string and create a file object but when I try to get the list of files inside the directory it returns a null to the array of strings.

I broke down the code and used the debugger in netbeans found out, when it did the SecurityManager check it wouldn't pass.

My question is are the files inside the project protected or there is no way to access them using the list() and listFiles() or am i doing something wrong? Also I ran the same script on my schools computer which they have windows 7 the code above worked. But when i ran it on my mac and even 2 win xp machines it just didn't work? why is that ?

I hope this makes sense i am just stuck here still a new to java

Thanks in Advance.

+2  A: 

The class to getResource(String) is returning a URL to images but there's no guarantee that this is a file URL (beginning "file:"). If your class is embedded within a jar file this certainly won't be the case, hence why it fails in some situations and not others.

If your intention here is to actually make a portion of a file system visible to the user then I'd recommend avoiding getResource altogether, which is typically more useful when your application wishes to locate and load resources such as icons or config files.

Instead, you could use JFileChooser, which is a rich Swing component for navigating the file system and selecting files.

Adamski