phaze0
phaze0

Reputation: 2008

How do I get a list of files in a java applet?

I am working on a collaborative project in Java, and thought it would be easiest to have it as an applet embedded in a webpage, and then everyone can add their child classes (of bonuses, enemies, etc) as they make them into the respective folders. And to make this work, I wanted the applet to check the folders on the website, gather the names of the files in each folder, and then put those names of the classes into an array as they'd each be randomly generated from this.

I originally tried making a File object and calling .listFiles() to get it into an array, but the file object would not recognize the path I gave it, getCodeBase().toString()+"bonus.txt", so I tried just putting the names of all of the classes that would be in a folder in a .txt file, opening the file, and just reading each line. This would work in eclipse, but when I uploaded the .class and .txt files to the website, I got a permissions error, so i put the class into a .jar, self signed it and uploaded it again but the applet would not work, it just froze.
Any time I did not have a file retreval statement, in or out of a .jar, the applet would work just fine, but if I had those lines of code it would freeze or give an error.

I've tried new scanner(new file("bonus.txt")); different variations of buffered readers found through google of similar issues, as well as different ways of loading the address through File class, but none of them have worked.

All I have been trying to get the applet to do this far is just load a .txt file (in the same directory as the .class file), read the contents and print them in the applet, with no success. Much appreciated if you could point me in the right direction.

Upvotes: 1

Views: 734

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

A File established by a (trusted) applet will point to a location on the file-system of the end user's computer (which probably will not exist). File objects can never point back to the server, that is not how they work.

To access resources from an applet, you would generally use an URL instead. E.G.

URL urlToList = new URL(getCodeBase(), "bonus.txt");
Scanner scanner = new Scanner(urlToList.openStream());

Note that neither of those lines would require the applet to be signed/trusted.

Upvotes: 3

Related Questions