Search code examples
javalibgdxsavelinefilehandle

Libgdx FileHandle reading and writing more than one line


Nice and easy question.. Im using filehandle to write and read scores.. wins and lossess.. but unlike a buffered reader you cant use read.line(); so how do you write and read lines in filehandler?? thanx here is the code

    private void writeSaveData()
{
    winstring = Integer.toString(wins);
    lossstring = Integer.toString(losses);

    FileHandle scores = Gdx.files.local("Score");
    scores.writeString(winstring, false);
    // I want to add another line here for lossess
}


private void loadScores()
{
    FileHandle scores = Gdx.files.local("Score");
    winstringread= scores.readString(winstring);
    wins = Integer.parseInt(winstringread);
    // same here add line to read lossess
}

Solution

  • For libgdx and this specific problem you are describing. You can read and write the strings whole and parse on delimiters.

    Non Human Readable. What we are doing here is taking and using String format so we can clearly see how the line will be written. We are making the winning score first and losses second, So if I win 10 and they lost 5 the string will look like this 10=5. This will be save into the file. When we read the file back we read 10=5 and then split this string up on =and are left with two strings 10 and 5. We can then parse these to integers.

    private void writeSaveData()
    {
        String saveString = String.format("%d=%d", wins, losses);
        FileHandle scores = Gdx.files.local("Score");
        scores.writeString(saveString, false);
    }
    
    
    private void loadScores()
    {
        FileHandle scores = Gdx.files.local("Score");
        String loaddedString = scores.readString(winstring);
        String[] scores = loadedString.split("=");
        wins = Integer.parseInt(scores[0]);
        losses = Integer.parseInt(scores[1])    
    }