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()) != nu开发者_高级运维ll) {
//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 );
}
}
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.
This will always be true: "Name" != "Name" || " "Email" != "Name"
if(! (line.trim().equals(name) || line.trim().equals(email)) ){
}
The other posters are correct. You should probably read this.
精彩评论