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

2012/11/1

How can I save the world into text file and load it again

1
2
CKL CKL

2012/11/1

#
I know I have to use file I/O but I don't like how to use it. Anyone can teach me how to implement file I/O to capture the information on the world into a txt file?
darkmist255 darkmist255

2012/11/1

#
First thing you need to know is that the text files would have to be in the project folder to be readable from the Gallery, Java won't let you read files on your computer from an applet on the internet unless it's a signed applet, which Greenfoot wouldn't let you upload since not all people can be trusted with file access. But if you're fine with that, then it's definitely possible, I've done this for a project before. Basically, first thing you need is something to read the lines and put them somewhere you can access them, this is the method I use:
public static List readText(String reqfile)// throws IOException
    {
        FileInputStream fis = null;
        BufferedReader r = null;
        List lines = new ArrayList();
        try
        {
            if(reqfile != null)
            {
                fis = new FileInputStream(reqfile);
                r = new BufferedReader(new InputStreamReader(fis));
            
                String linetmp;
                while((linetmp = r.readLine()) != null)
                {
                    lines.add(linetmp);
                }
            }
        }
        catch(IOException e)
        {
            System.err.println("Caught IOException: " + e.getMessage());
        }
        return lines;
    }  
Then you just make a method to interpret the Strings. This is up to you what you want it to mean, but with that method you isolate each line as a String. Hope that helps!
CKL CKL

2012/11/1

#
then how can I output a text file just like a game save in the project folder??
CKL CKL

2012/11/1

#
I have typed a few codes, How can I achieve the command lines mention
    public void load() throws Exception   
    {            
            //<----here I want to load the save in "game.txt"   
    }     
    

    public void save() throws Exception 
    {
        FileWriter writer = null;
        writer = new FileWriter("game.txt");
        writer.write(???);  //<---here I want to save the what world is like at this moment
        writer.close();
    }
darkmist255 darkmist255

2012/11/1

#
For loading, first you would want to specify what file to look at
fis = new FileInputStream("game.txt");  
r = new BufferedReader(new InputStreamReader(fis));  
Then you would want to read all the lines and store them, one at a time, in a List
List lines = new ArrayList(); //This is where we will store the Strings

String linetmp;
while((linetmp = r.readLine()) != null)//This reads the next line, saves it as linetmp, then continues as long as it isn't null
{
    lines.add(linetmp); //This adds the String to our List
}
This would give you your list of Strings. For saving, you have the right idea with FileWriter, but I would add one parameter so it doesn't append to the end of the file
writer = new FileWriter("game.txt", false); //This makes it overwrite the old file
Then you would make a List containing the Strings you want to write and then you would do something like
List linesToWrite = //your lines

for(int i = 0; i < linesToWrite.length; i++)
{
    if(linesToWrite[i] != null)
    {
        writer.write(linesToWrite[i]);
        writer.newLine();
    }
}
writer.close();
If you have any questions about any of that I can explain in more detail!
CKL CKL

2012/11/2

#
I have edited something but still don't know how to achieve it. I want the numbers and true/false store in two separate array which can be call back easily.
       public void load() throws Exception     
    {  
        File inputFile = new File("a.txt");  
        Scanner input = new Scanner("a.txt");  
        int [][] num;  // <--Could I do this to store a nx4 array where [0][0] is like the text file shown eg. 0  
        String [][] state;//<-- Could I do this to store a nx2 array which only contain true and false  
          
boolean exists = inputFile.exists();
        if( exists ){   
            while(input.hasNext()){    
                 startPerson = ???; //<--How can I get the first number in the text    
                 for(int row=0;row<the number of line in the text ; row++){//how to set the number of line in the text    
                      for(int col=0;col<2;col++){    
                           String state[row][col] = input.next(); //<--I want this to store true false in that nx2 array    
                      }    
                 }    
                 for(int row=0;row<the number of line in the text ; row++){ //how to set the number of line in the text    
                      for(int col=0;col<2;col++){    
                         num[row][col] = input.nextInt(); // I want to store the numbers into a array starting to read from the second line    
                      }    
                 }    
                 for (int i=0;i<number of line in the text;i++) { //this loop need to be correct but dun know how    
                     Object c = new Object(num[i][0], num[i][1], state[i][0]);      
                     state[i][1] = c.selected;    
                     addObject(c, num[i][2], num[i][3]);    
                 }                                      
            }
                 input.close();    
            }else return;  
My text file...(a.txt)
1 0 6 false 7 1 false 0 5 false 0 3 false 0 5 false 5 0 false 0 4 true 4 2 false 0 4 false 4 0 false 0 3 true 3 3 true 0 3 true 5 1 false 0 2 false 7 0 false 0 2 true 6 1 false 0 1 false 1 2 false 0 1 false 2 1 false 0 0 false 0 1 false 0 0 false 6 2 false 0 0 false 2 3 false 0 0 false 3 1 false 0 0 false 7 3 false 1 6 false 5 3 false 1 5 false 5 2 false .......(There maybe more or less rows)
and I use the following to write the file out as a.txt
....
writer.println(startPerson);
        for(int i=0;i<numOfObjects;i++){
            Object object = objectss.get(i);
            writer.print(object.color() + " " + object.which() + " " + object.ex() + " " + object.getX() + " " + object.getY() + " " + object.selected);
            writer.println();
        }        
        writer.close();
SPower SPower

2012/11/2

#
@CKL Look at this scenario for saving and loading, it has already done many things.
danpost danpost

2012/11/2

#
You could avoid a lot of the guess-work by storing EVERYTHING in a single string. First, you will have one, and always only one, string stored. Second, the length of the string can easily be retrieved to get the number of 'lines' as you have them displayed above. Each line can be stored as ONE character (I am assuming, however, that the maximum for any number is 7). It would take 3 bits for each number and 1 bit for each boolean (3 * 4 + 1 * 2 = 14), which leaves 2 bits to spare. You can set the second highest bit on to avoid conflict with char 13 (the return character).
 // to create the string to save
String text = "";
text += (char) startPerson;
for (int i = 0; i < lineCount; i++)
{
    int value =  1; // to set second highest bit
    value = (value * 2) + (state[i][1] ? 1 : 0);
    value = (value * 8) + num[i][3];
    value = (value * 8) + num[i][2];
    value = (value * 2) + (state[i][0] ? 1 : 0);
    value = (value * 8) + num[i][1];
    value = (value * 8) + num[i][0];
    text += (char) value;
}
// to break the string back up after reading it back in as 'text'
lineCount = text.length() - 1;
if (lineCount != -1))
{
    startPerson = (int) text.charAt(0);
    text = text.substring(1);
    for (int i = 0; i < lineCount; i++)
    {
        int value = (int) text.charAt(i);
        num[i][0] = value % 8;
        value = value / 8;
        num[i][1] = value % 8;
        value = value / 8;
        state[i][0] = value % 2 == 1;
        value = value / 2;
        num[i][2] = value % 8;
        value = value / 8;
        num[i][3] = value % 8;
        value = value / 8;
        state[i][1] = value % 2 == 1;
    }
}
You can place each part in methods called 'codeGameData' and 'decodeGameData', if you wish Hope this helps.
CKL CKL

2012/11/3

#
it shows it cannot find var. lineCount
CKL CKL

2012/11/3

#
Sorry I have a question to ask how can I store this text file(I have editted) into a single string the first number means the game start or not from -1 to 1, 0 start by first player, 1 start by second player, -1 means the game has not yet started the second number means how many rows in the below array. How can I store this array into string
0 32 0 6 4 2 0 0 0 5 1 1 0 0 0 5 6 2 0 0 0 4 1 3 0 0 0 4 7 1 0 0 0 3 3 0 0 0 0 3 7 0 0 0 0 2 5 2 0 0 0 2 5 1 0 0 0 1 2 2 0 0 0 1 6 0 0 0 0 0 4 0 0 0 ......
CKL CKL

2012/11/3

#
I have a problem in getting it done, it seems I have some problem as it can't load the text file but when I press complie, it doesn't show any mistake
    public static int [][] num;
    public static int startPerson = -1;
    public static int lineCount = 0;
 .....
            String text = ""; 
            int line=0;
            text += (char) startPerson;
            while(input.hasNextLine()==true)
            {
                line++;
            }
             
            for (int i = 0; i < line; i++)  
            {
                int value =  1; // to set second highest bit  
                value = (value * 2) + num[i][0]; 
                value = (value * 7) + num[i][1];  
                value = (value * 8) + num[i][2];  
                value = (value * 4) + num[i][3];
                value = (value * 2) + num[i][4];  
                value = (value * 2) + num[i][5];  
                text += (char) value;  }
                  
           
            boolean flipState;
                
            lineCount = text.length()-2;
            if(lineCount != -1)
            {
                startPerson = (int) text.charAt(0);
                
                text = text.substring(2);
                 for(int i=0;i<lineCount;i++){  
                     
                         
                         int value = (int) text.charAt(i);
                         num[i][0] = value % 2;  
                         value = value / 2; 
danpost danpost

2012/11/3

#
The first number: since it has three possibilities (-1, 0, and 1) you can add 1 to it before saving it and subtract 1 after reading it. The second number: you do not need to save this; the length of the string will tell you this. Lines 3 and 5 through 8 (your reference to 'line'): you should either already have a value for this or be able to get this value from the world (you may have to add the sizes of lists of objects to acquire the value; and you can use 'lineCount' for its name). Truthfully, you really do not even need the count; just build the string until you are done (then you will be able to get the count from the length of the string minus one). Even then, there is no need to have a reference to the count, as you know you need to write just one String to the file. Get a list of each type object and save them to the string, something like the following
int objNum = 0;
for (Obj obj : getObjects(Object1.class))
{
    Object1 o1 = (Object1) obj;
    text += encode(o1.color(), o1.which(), o1.ex, o1.getX(), o1.getY(), o1.selected);
}
where the method encode is a method with the previous encoding code that returns a 'char' or a one character String object. Repeat the 'for' loop for each of the different objects, incrementing 'objNum' between each.
CKL CKL

2012/11/4

#
Sorry for making you confuse about my question. In fact, from now what I know is I have three problems need to be solve. one is how can I make this text file into a string like what you did in the beginning eg. 1 0 6 0 0 0 0 0 5 0 1 0 0 0 5 0 3 0 0 0 4 6 0 0 0 0 4 1 0 0 0 ...... 1 0 6 0 0 0 0 0 5 0 1 0 0 0 5 0 3 0 0 0 4 6 0 0 0 0 4 1 0 0 0 0 3 0 2 0 0 0 3 4 2 0 0 0 2 2 1 0 0 0 2 2 0 0 0 0 1 3 3 0 0 0 1 7 1 0 0 0 0 4 1 0 0 ....... Second, how can I get the number of line in the string? In the above text file, could I use text.length() since I have some functions need to be done in every line? Third, how can I call each number in the string back in every line. Can I use "int value = (int) text.charAt(i);" in a for loop where "i" is the position of the numbers in the string of each line? The for loop is doing every line in the String.
danpost danpost

2012/11/4

#
CKL wrote...
how can I make this text file into a string like what you did in the beginning eg. 1 0 6 0 0 0 0 0 5 0 1 0 0 0 5 0 3 0 0 0 4 6 0 0 0 0 4 1 0 0 0 ......
With each character in single quotation marks, your text string will contain: '1', '0 6 0 0 0 0', '0 5 0 1 0 0', '0 5 0 3 0 0', '0 4 6 0 0 0', '0 4 1 0 0 0'..... Just follow the guidelines of what I provided earlier to turn the values into characters to make up the string.
CKL wrote...
how can I get the number of line in the string? In the above text file, could I use text.length() since I have some functions need to be done in every line?
Yes, once you have read the one record of the file (the text string) in, you can use 'length()' on the string to find out how many characters are in the string. It will be one more than the number of lines saved in the string.
CKL wrote...
Third, how can I call each number in the string back in every line. Can I use "int value = (int) text.charAt(i);" in a for loop where "i" is the position of the numbers in the string of each line? The for loop is doing every line in the String.
Again, just follow the guidelines of the code I provided above to 'decode' the string. Decode the first character seperately, then use the 'for' loop for the rest.
CKL CKL

2012/11/5

#
i have no problem in creating the string and assigning the startPerson now, but one thing left is about "getting something from the list" for example: String thirdLine = text.get(2); show "0 5 0 3 0 0" How to get the number in this line in this example such as int a = ??? <--the first number in this line eg. "0" int b = ???<-- the second number in this line eg. "5" int c = ???<-- the third number in this line eg. "0" int d = ???<-- the forth number in this line eg. "3" int e = ???<-- the fifth number in this line eg. "0" int f = ???<-- the sixth number in this line eg. "0" since I will use a for loop to do it, once I tackle one line then the other line is also ok.
There are more replies on the next page.
1
2