我正在尝试
我的问题是第4步和第5步。我也不确定我是否正确订购。 代码如下所示。
public static void deleteAccount(String accountNumber) throws Exception {
File accountFile = new File("Account Information.txt");
File tempFile = new File("Temp Account Info.txt");
BufferedReader br = new BufferedReader(new FileReader(accountFile));
FileWriter tempFw = new FileWriter(tempFile, true);
PrintWriter tempPw = new PrintWriter(tempFw);
String line;
try {
while ((line = br.readLine()) != null) {
if(!line.contains(accountNumber)) {
tempPw.print(line);
tempPw.print("\r\n");
}
}
**FileWriter fw = new FileWriter(accountFile);
PrintWriter pw = new PrintWriter(fw);
tempFile.renameTo(accountFile);
accountFile.delete();
fw.close();
pw.close();
tempFw.close();
tempPw.close();
} catch (Exception e) {
System.out.println("ERROR: Account Not Found!");
}
}
完整代码可在以下网址找到:https://hastebin.com/eposapecep.java
非常感谢任何帮助!
我知道我没有正确检查"未找到帐户"并且会在命名问题之后尝试解决这个问题。
提前致谢!
答案 0 :(得分:1)
使用File的 renameTo()方法。
try {
File file = new File("info.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String str = br.readLine();
File file2 = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file2));
bw.write(str);
br.close();
bw.close();
if (!file.delete()) {
System.out.println("delete failed");
}
if (!file2.renameTo(file)) {
System.out.println("rename failed");
}
} catch (IOException ex) {
ex.printStackTrace();
}
上面的代码读取info.txt的第一行,将其写入temp.txt,删除info.txt,将temp.txt重命名为info.txt