简体   繁体   中英

Can't save List<> to sd-card

Here is what I do when I save my score to the highscore.

public void save() {
    try {
        BufferedWriter fw = new BufferedWriter(new FileWriter(myDir
                + "/HIGHSCORE.txt"));
        for (Integer i : scores) {
            System.out.println(i);
            fw.write(i);
            fw.newLine();
            fw.flush();
        }
        fw.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void beforeSave() {
    List<String> stringReader = new ArrayList<String>();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(myDir + "/HIGHSCORE.txt"));
        String s = "";
        while ((s = br.readLine()) != null) {
            System.out.println("LINE: " + s + "\n");
            scores.add(Integer.parseInt(s));
        }
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I have two methods to save and load the data information, beforeSave() do I use in the onResume() mwthod, and save() have I put in the onPause(). It crash when I call the onStop()(shut down the program), And I'm prette sure that befoeStart() doesn't work eather. I have use the Scanner class, to use the method nextInt(), but it doensn't work :(. And when I just save one score, it workds. What on earth do I do wrong?

PS. I'm now sure if I have to use flush(), but it doesn't work befoe eather.

//Daniel

Change fw.write(i); to fw.write(i.toString());

Rationale:
Currently your code saves values into a file in binary format but reads them in text format. You have to use the same format to fix the issue. Saving in text format makes reading highscores.txt much easier so I provided that solution.

Here's my test code:

package com.me;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class Main extends Activity
{
    private static String FILE_NAME = "HIGHSCORES.txt"; // Added this for better maintainability
    private String myDir;
    private List<Integer> scores;


    @Override public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Folder in SD card
        myDir = Environment.getExternalStorageDirectory() + "/TwoDee"; // Just a random name

        // Initialize Integer list with some values
        scores = new ArrayList<Integer>();
        scores.add(new Integer(5));
        scores.add(new Integer(9));
        scores.add(new Integer(11));

        // Make sure there's the file or our test crashes. I hope you have similar code elsewhere?
        try
        {
            File folder = new File(Environment.getExternalStorageDirectory(), "TwoDee");
            if (folder.exists() == false)
                folder.mkdirs();

            File file = new File(folder, FILE_NAME);
            if (file.exists() == false)
                file.createNewFile();
        }
        catch (Exception e)
        {
            System.out.println("Fail"); // Blunt :)
        }
    }

    @Override public void onResume()
    {
        beforeSave();
        super.onResume();
    }

    @Override public void onPause()
    {
        save();
        super.onPause();
    }

    @Override public void onStop()
    {
        super.onStop();
    }

    public void save()
    {
        Log.v("TwoDee", "save...");
        try
        {
            BufferedWriter fw = new BufferedWriter(new FileWriter(myDir + "/" + FILE_NAME));
            for (Integer i : scores)
            {
                Log.v("TwoDee", i.toString());
                fw.write(i.toString());
                fw.newLine();
                //fw.flush(); // This is not really needed.
            }
            fw.close();

        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        Log.v("TwoDee", "...save");
    }

    public void beforeSave()
    {
        //List<String> stringReader = new ArrayList<String>(); // Not needed...
        BufferedReader br = null;
        Log.v("TwoDee", "beforeSave...");
        try
        {
            br = new BufferedReader(new FileReader(myDir + "/" + FILE_NAME));
            String s = "";
            while ((s = br.readLine()) != null)
            {
                Log.v("TwoDee", s);
                //System.out.println("LINE: " + s + "\n"); // Not needed...
                scores.add(Integer.parseInt(s));
            }
        } catch (FileNotFoundException e1)
        {
            e1.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        Log.v("TwoDee", "...beforeSave");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM