开发者

File gets overwritten on program restart Android

I am trying to write out some data to a file. However, every time I restart my program, I think it is overwriting the original file (making a new one?) Here is a snippet of code where I instantiate things. Is there something I can change so that the file doesn't get overwritten everytime? something like if file.doesExist??

try {
        File root = Environment.getExternalStorageDirectory();
        if(root.canWrite()){
        File highscoresFile = new File(root, "names.txt");
        FileWriter writer = new FileWriter(highscoresFile);
        BufferedWriter out = new BufferedWriter(writer);
        //out.newLine();
        out.append(name);
        out.close();
        }
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printSta开发者_运维知识库ckTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


You are likely overwriting the file. You can append to the end of the file with the FileWriter by using a different constructor.

Instead use

FileWriter writer = new FileWriter(highscoresFile, true);

The boolean at the end tells you whether or not to append to the end of the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜