如何从文件中删除特定行

时间:2018-01-11 17:23:22

标签: java android file bufferedreader fileoutputstream

我正在尝试从文件中删除特定行,但是当我运行它时,它会返回我删除的所有文件。更具体一点,我在视频片段中有一个喜欢的按钮,我希望当用户按下它时,在文件中写入视频标题(已经完成),并在取消它时删除它....

my.java类是:

@dev
Scenario: WhiteboxTest - Process Topic Message - Yes
    Given the storage account is empty
    | Storage account |
    | mydemo |
    And the logic app is enabled
    When a message is submitted to the topic
    | Topic |
    | TestTopic |
    Then the logic app will receive the message

2 个答案:

答案 0 :(得分:0)

所以,问题出在下面的代码行,你试图打开文件进行同时读写

File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
    BufferedReader br = new BufferedReader(new FileReader(file));

相反,我建议你完全读取你的文件,然后在最后你应该写入文件(覆盖)。

try {
    File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");

    if (file.exists()) {
        BufferedReader br = new BufferedReader(new FileReader(file));
        StringBuilder text = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            if (!line.equals(g) && !g.equals("\n")){
                text.append(line);
                text.append('\n');
            }
        }
        br.close();

        //start writing from here
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
        outputStreamWriter.write(text.toString());
        outputStreamWriter.flush();
        outputStreamWriter.close();
    } 
} catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
}

答案 1 :(得分:0)

这一行:

FileOutputStream fos = new FileOutputStream(file);

重置文件的内容(即用空文件替换它)。我建议您添加日志记录和/或调试代码,以便更好地了解正在发生的事情。