Search code examples
javabufferedreaderprintwriter

How to read a certain line with a BufferedWriter


I am working on a simple save system for my game, which involves three methods, init load and save.

This is my first time trying out reading and writing to/from a file, so I am not sure if I am doing this correctly, therefore I request assistance.

I want to do this:

When the game starts, init is called. If the file saves does not exist, it is created, if it does, load is called.

Later on in the game, save will be called, and variables will be written to the file, line by line (I am using two in this example.)

However, I am stuck on the load function. I have no idea what do past the point I am on. Which is why I am asking, if it is possible to select a certain line from a file, and change the variable to that specific line.

Here is my code, like I said, I have no idea if I am doing this correctly, so help is appreciated.

private File saves = new File("saves.txt");

private void init(){
    PrintWriter pw = null;

    if(!saves.exists()){
        try {
            pw = new PrintWriter(new File("saves.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }else{
        try {
            load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void save(){
    PrintWriter pw = null;

    try {
        pw = new PrintWriter(new FileOutputStream(new File("saves.txt"), true));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    pw.println(player.coinBank);
    pw.println(player.ammo);

    pw.close();
}

public void load() throws IOException{
    BufferedReader br = new BufferedReader(new FileReader(saves));
    String line;
    while ((line = br.readLine()) != null) {

    }
}

I was thinking of maybe having an array, parsing the string from the text file into a integer, putting it into the array, and then have the variables equal the values from the array.


Solution

  • Seems like your file is a key=value structure, I suggest you'll use Properties object in java. Here's a good example.

    Your file will look like this:

    player.coinBank=123
    player.ammo=456
    

    To save:

    Properties prop = new Properties();
    prop.setProperty("player.coinBank", player.getCoinBank());
    prop.setProperty("player.ammo", player.getAmmo());
    //save properties to project root folder
    prop.store(new FileOutputStream("player.properties"), null);
    

    Then you'll load it like this:

    Properties prop = new Properties();
    prop.load(new FileInputStream("player.properties"));
    
    //get the property value and print it out
    System.out.println(prop.getProperty("player.coinBank"));
    System.out.println(prop.getProperty("player.ammo"));