从文件中删除行
我有以下代码,但它似乎不起作用..有人知道为什么吗?基本上我正在创建一个新文件,其中包含除包含我试图删除的两个字符串的行之外的所有行,但代码似乎不起作用。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的||需要是 &&。
即,
否则,如果该行不等于姓名或电子邮件,则会将其写入。
Your || needs to be an &&.
i.e.
Otherwise if the line isn't equal to either of name or email, it will be written.
这永远是真的:
“姓名”!=“姓名”|| " "电子邮件" != "姓名"
This will always be true:
"Name" != "Name" || " "Email" != "Name"