从文件中删除行

发布于 2024-10-04 23:08:09 字数 958 浏览 4 评论 0原文

我有以下代码,但它似乎不起作用..有人知道为什么吗?基本上我正在创建一个新文件,其中包含除包含我试图删除的两个字符串的行之外的所有行,但代码似乎不起作用。

public void removelines(String name, String email){
try{
    //Create objects for our file and the temp file.
    File f = new File("addy");
    File temp = new File(f.getAbsolutePath()+ "temp");
    //Our readers.
    BufferedReader buf = new BufferedReader(new FileReader("addy"));
    PrintWriter print = new PrintWriter(new FileWriter(temp));

    String line = null;

    while ((line = buf.readLine())  != null) {
        //put all data not equal to that to be removed into the new file.
            if(!line.trim().equals(name) || !line.trim().equals(email)){
                print.println(line);
                print.flush();
            }
            }
        print.close();
        buf.close();
        f.delete();
        temp.renameTo(f);
    } catch (Exception e){
        JOptionPane.showMessageDialog(null, "ERROR:" + e );
    }
}

I've got the following code but it doesn't seem to be working.. anyone have any ideas why? basically I'm creating a new file containing all the lines except those which contain the two strings I'm trying to remove but the code doesn't seem to be working.

public void removelines(String name, String email){
try{
    //Create objects for our file and the temp file.
    File f = new File("addy");
    File temp = new File(f.getAbsolutePath()+ "temp");
    //Our readers.
    BufferedReader buf = new BufferedReader(new FileReader("addy"));
    PrintWriter print = new PrintWriter(new FileWriter(temp));

    String line = null;

    while ((line = buf.readLine())  != null) {
        //put all data not equal to that to be removed into the new file.
            if(!line.trim().equals(name) || !line.trim().equals(email)){
                print.println(line);
                print.flush();
            }
            }
        print.close();
        buf.close();
        f.delete();
        temp.renameTo(f);
    } catch (Exception e){
        JOptionPane.showMessageDialog(null, "ERROR:" + e );
    }
}

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

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

发布评论

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

评论(2

几度春秋 2024-10-11 23:08:09

你的||需要是 &&。

即,

!line.trim().equals(name) && !line.trim().equals(email)

否则,如果该行不等于姓名或电子邮件,则会将其写入。

Your || needs to be an &&.

i.e.

!line.trim().equals(name) && !line.trim().equals(email)

Otherwise if the line isn't equal to either of name or email, it will be written.

っ〆星空下的拥抱 2024-10-11 23:08:09

这永远是真的:
“姓名”!=“姓名”|| " "电子邮件" != "姓名"

if(! (line.trim().equals(name) || line.trim().equals(email)) ){
}

This will always be true:
"Name" != "Name" || " "Email" != "Name"

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