4

所以我使用文件来保存我的程序的一些分数,但问题是我不能只打印它们。我尝试了几件事,但没有找到正确的,这是我的代码:

try{
        String FILENAME = "FrogScoreFile";
        FileInputStream fos = openFileInput(FILENAME);
        byte[] b = new byte[1];
        fos.read(b);
        fos.close();
        String score= String b;
        game5HighScore.setText(b);
        }catch (java.io.FileNotFoundException e) {
        } catch (IOException e) {
                e.printStackTrace();
    }
4

2 回答 2

15

Byte array您可以通过创建new string对象转换为字符串。

byte[] b = new byte[1];
fos.read(b);
fos.close();
String message = new String(b);
于 2012-05-03T09:21:13.057 回答
0
try{
        String FILENAME = "FrogScoreFile";
        FileInputStream fos = openFileInput(FILENAME);
        BufferedReader br = new BufferedReader(new InputStreamReader(fos));
        String yourText = br.readLine();
        br.close();
        game5HighScore.setText(yourText);
    }catch (java.io.FileNotFoundException e) {
    } catch (IOException e) {
            e.printStackTrace();
}

顺便一提。为什么不使用 SharedPreferences 或 SQLite 数据库保存您的分数?

共享偏好指南。

public static void saveScore(Context context) {
    final SharedPreferences.Editor editor = context.getSharedPreferences(
            "settings", Context.MODE_PRIVATE).edit();
    editor.putInt("score", 100);
    editor.commit();
}

public static int readScore(Context context) {
    final SharedPreferences sp = context.getSharedPreferences("settings",
            Context.MODE_PRIVATE);
    return sp.getInt("score", 0);
}
于 2012-05-03T09:19:04.170 回答