String id = filedda.getText();
String pass= filedda1.getText();
try {
File inputFile = new File("E:/yoo.txt");
File tempfile = new File("E:/mytempfile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempfile));
String CurrentLine;
while((CurrentLine = reader.readLine())!=null){
if(CurrentLine.contains(id+pass)){
CurrentLine= CurrentLine.replace(id+pass, "");
}
writer.write(CurrentLine);
reader.close();
writer.close();
inputFile.delete();
tempfile.renameTo(inputFile);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我想要它做的是:它将从文件中删除id + pass的字符串。
如果情景如此,它正在正确地进行,
abc
cde
我的id+pass= cde
文件输出:abc
但是如果是id+pass= abc
,那么整个文件输出就变成什么了。
答案 0 :(得分:3)
您应该只在while循环后关闭文件:
while(){
//...
}
reader.close();
writer.close();
答案 1 :(得分:2)
您正在提前关闭文件。 在这附近:
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
此外,如果您正在使用Swing
,请确保其EDT安全。
答案 2 :(得分:0)
创建FileWriter
时,您应该提供true作为参数,以表明您希望附加数据。
Shown here.
e.g:
BufferedWriter writer = new BufferedWriter(new FileWriter(tempfile, true));
如果我理解你的问题。
答案 3 :(得分:-1)
试试这段代码:
String id = filedda.getText();
String pass= filedda1.getText();
try {
File inputFile = new File("E:/yoo.txt");
File tempfile = new File("E:/mytempfile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempfile));
String CurrentLine;
while((CurrentLine = reader.readLine())!=null){
if(CurrentLine.contains(id+pass)){
CurrentLine= CurrentLine.replace(id+pass, "");
}
}
writer.write(CurrentLine);
reader.close();
writer.close();
inputFile.delete();
tempfile.renameTo(inputFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}