This site requires JavaScript, please enable it in your browser!
Greenfoot back

Accessing "files" in my scenario

Something that many Greenfoot programmers find out by accident is that you can't access files from a Java applet (including Greenfoot scenarios which are uploaded to the greenfoot.org website). This is a security restriction imposed on all Java applets; it would be dangerous if arbitrary applets could access files on your computer.

The good news is: If there are files inside your scenario's folder, they will be bundled up in the applet before it is uploaded. You can then use code like the following to access their contents:

InputStream input = getClass().getClassLoader().getResourceAsStream("filename.txt");

You'll need to import java.io.InputStream. You can use the input stream much like a FileInputStream which you would use to read from a file. Often, you'll want to wrap it with an InputStreamReader.

Two things to note:

  1. You should specify the full path to the file within your scenario, using forward slashes (" / ") as a path separator. You do not need an initial slash. Backslashes will not work!
  2. File names will be case sensitive - you must not write "FILENAME.TXT" if the file name is really "filename.txt"

Also, there is no way to write to a file; you can only read from files which have been bundled into your scenario.

For a more complete example, see the filereader scenario.