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

2018/2/8

How to write/read file

DrCrane DrCrane

2018/2/8

#
Hello again, I've been searching the forums for a class or anything that is able to read and write a file to the project directory. I have no idea how to use them though. I only need to know how to use them (for example this one: http://www.greenfoot.org/scenarios/7647 ). If you're wondering why I need it, it is because I have to make a game for a school project and want to include the ability to save (not graded). Any help is appreciated
danpost danpost

2018/2/8

#
Reading a local file can be done anywhere -- on your local network or on the site. Writing to a file can only be done locally, provided you have permission (you cannot write to a file on the site. I did not look to see how the mentioned scenario works; but, I do have some scenarios uploaded that do read files. Basically, they use code similar to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
try
{
    InputStream input = getClass().getClassLoader().getResourceAsStream(filename); // open input stream
    br = new BufferedReader(new InputStreamReader(input)); // wrap the stream within a BufferedReader object
}
catch (Exception e) { System.out.println("File not found: "+filename); return; } // for failure to open stream
// attempt to read in the lines of text
try
{
    String line = null; // sets up a local field for each line of text
    while ((line = br.readLine()) != null)  lines.add(line); // read each line and add them to the 'lines' list
    br.close(); // close the BufferedReader object
}
catch (Exception e) { try { br.close(); } catch (Exception f) {} } // close file if read error occurred
where 'filename' is a String object containing the name of the file (including suffix) and 'lines' is declared as a new List object:
1
List<String> lines = new ArrrayList<String>();
The following imports are needed:
1
2
3
import java.util.List;
import java.util.ArrayList;
import java.io.*;
You would use an OutputStream object wrapped in a BufferedWriter object to write to a file.
DrCrane DrCrane

2018/2/19

#
Sorry for the late reply, I have no idea how to implement this. When pasting the code in every line that contains "br" gives a cannot find symbol error. And where do I put the lines List? It also gives an error with the ArrayList<String> part. Specifically ArrayList. I do have everything imported that you told me to.
danpost danpost

2018/2/19

#
Oh, I guess I missed the first line:
1
BufferedReader br = null;
The List line can be placed along with this one.
DrCrane DrCrane

2018/2/19

#
That just leaves me with a single error:
1
List<String> lines = new ArrrayList<String>();
gives "cannot find symbol- class ArrrayList" EDIT: Figured it out. ArrayList has 3 r's in your code. So it should be ArrayList in stead of ArrrayList
You need to login to post a reply.