Android 程序重启时文件被覆盖

发布于 2024-11-06 13:47:13 字数 720 浏览 4 评论 0原文

我正在尝试将一些数据写入文件。然而,每次我重新启动程序时,我认为它会覆盖原始文件(制作一个新文件?)这是我实例化事物的代码片段。我可以更改一些内容以使文件不会每次都被覆盖吗?类似 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.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

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.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

披肩女神 2024-11-13 13:47:13

您可能会覆盖该文件。您可以使用不同的构造函数将 FileWriter 附加到文件末尾。

相反,使用

FileWriter writer = new FileWriter(highscoresFile, true);

末尾的布尔值告诉您是否附加到文件末尾。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文