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

2013/6/6

Reading textfiles

Zamoht Zamoht

2013/6/6

#
Is it possible to upload a scenario with a textfile in the scenarios "bundle". If it is possible how would i go around accessing the file from the bundle? I might be able to find at way to read the file on my own but I don't know how to access (find) the file nor if it possible.
Gevater_Tod4711 Gevater_Tod4711

2013/6/6

#
To read and write files you can use this demo but on a webside that will not work because it's impossible to save or load files if you run your application on the internet.
danpost danpost

2013/6/6

#
To make sure you understand correctly. Reading and writing files are possible locally (whether using Greenfoot or as a jar application). On the site, writing files is not allowed due to security restriction within Java applets; however, reading files is allowed provided that the file is located within the scenarios "bundle" (accessing files outside the scenarios folder is prohibited). The following is one possible way to access a text file:
// with these imports
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
// using this array to hold the text from the file
private ArrayList<String> lines = new ArrayList<String>();
// BufferedReader br = null;
try
{
    URL path = getClass().getClassLoader().getResource("filename.txt");
    InputStream input = path.openStream();
    br = new BufferedReader(new InputStreamReader(input));
}
catch (Exception e) { System.out.println("Scenario file missing"); return; }
try
{
    String line = null;
    while ((line = br.readLine()) != null)  lines.add(line);
    br.close();
}
catch (Exception e) { try { br.close(); } catch (Exception f) {} }
This will access a text file called "filename.txt" located in the scenario folder at the same level that the README file is located.
Zamoht Zamoht

2013/6/6

#
Thanks danpost thats exactly what i needed. Haven't tried the code yet but it looks promising.
You need to login to post a reply.