简体   繁体   English

如何从文件中删除特定行

[英]How to remove specific line from the file

I am trying to delete a specific line from a file, but when I run this, it returns me all the files, deleted. 我正在尝试从文件中删除特定行,但是当我运行它时,它将返回我所有已删除的文件。 More specific i have a favorite button at a video fragment and i want when user press it ,to write the title of video in file (already done) and when unpress it to delete it.... 更具体地讲,我在视频片段上有一个收藏夹按钮,我希望在用户按下它时,在文件中写入视频标题(已完成)以及在取消按下该按钮以将其删除时...。

my.java class is: my.java类是:

private void writeToFile(String g,Context context) {
    try {
        File file=new File("/data/data/com.holomedia.holomedia/config.txt");
        FileOutputStream fos = new FileOutputStream(file,true);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
        if (!file.exists()) {outputStreamWriter.write(g);}
        outputStreamWriter.append("\n"+g +"\n");
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}

private void deleteToFile(String g,Context context) {
    try {
        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));
            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();
            outputStreamWriter.write(text.toString());
        }
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.favorite:
            if(showingFirst==true) {
                Context context = getActivity();
                CharSequence text = "Added to Favorites";
                int duration = Toast.LENGTH_SHORT;
                item.setIcon(R.drawable.heart_off);
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                writeToFile(title,context);
                showingFirst=false;
            } else {
                Context context = getActivity();
                CharSequence text = "Deleted from Favorites";
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                deleteToFile(title,context);
                item.setIcon(R.drawable.heart_wh);
                showingFirst=true;
            }
            break;
        case R.id.home:
            Intent k=new Intent(getActivity(),MainActivity.class);
            Log.i(TAG, "onNavigationItemSelected: ");
            startActivity(k);
            break;
    }
    return false;
}

So, problem lies at below line of codes where you are trying to open file for Read and Write simultaneously 因此,问题出在以下代码行中,您试图同时打开文件以进行读取和写入

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));

Instead, I would suggest you to read your file completely and then at the end you should write to the file (overwrite). 相反,我建议您完全读取文件,然后最后应写入文件(覆盖)。

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());
}

This line: 这行:

FileOutputStream fos = new FileOutputStream(file);

resets contents of the file (ie replaces it with empty file). 重置文件内容(即用空文件替换)。 I recommend you add logging and/or debug your code so you will have a better understanding of what is going on. 我建议您添加日志记录和/或调试代码,以便对发生的事情有更好的了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM