读取和写入Android文件

时间:2011-09-21 21:20:20

标签: android

我正在学习Android,我正在制作一些基本的数学程序(游戏)。它有两个随机数,随机算子和30秒,可以尽可能多地解决数学问题。如果你解决问题,你得1分。

无论如何,我想获得用户已经制作的点数,并将其写入文件,然后再阅读它(现在只是为了记录它)。

当我点击按钮来编写文件时,它会,我收到此日志消息: 09-21 21:11:45.424:调试/写作(778):这是写日志:2

是的,好像它写道。哦,让我们读一读。

09-21 21:11:56.134:DEBUG /阅读日志(778):这是阅读日志:2

它读了它。

但是当我再次尝试编写时,它似乎会覆盖以前的数据。

09-21 21:17:19.183:DEBUG / Writing(778):这是写日志:1 09-21 21:17:28.334:调试/阅读日志(778):这是阅读日志:1

正如您所看到的,它只读取最后一个输入。

这是代码的一部分,我正在编写和阅读它。

public void zapisi() {
    // WRITING
    String eol = System.getProperty("line.separator");
    try {
        FileOutputStream fOut = openFileOutput("samplefile.txt",
                MODE_WORLD_READABLE);
        OutputStreamWriter osw = new OutputStreamWriter(fOut);

        osw.write(poenibrojanje+eol);
        //for(int i=0;i<10;i++){
        Log.d("Writing","This is writing log: "+poenibrojanje);
        //}

        //osw.flush();
        osw.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


private void citaj() {

    // READING

    String eol = System.getProperty("line.separator");
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(
                openFileInput("samplefile.txt")));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = input.readLine()) != null) {
            buffer.append(line + eol);
        }
        //TextView textView = (TextView) findViewById(R.id.result);
        Log.d("Reading log","This is reading log:"+buffer);
        System.out.println(buffer);
        //tvRezultat.setText(buffer.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:1)

您可以使用openFileOutput(“samplefile.txt”,MODE_APPEND)