将文件重命名为现有的java文件
我正在努力将文件重命名为现有的java文件,java,file,delete-file,file-rename,Java,File,Delete File,File Rename,我正在努力 创建临时文件“Temp Account Info.txt” 将现有帐户文件“Account information.txt”中的信息写入“Temp Account Info.txt” 省略某些信息 删除“Account Information.txt” 将“Temp Account Info.txt”重命名为“Account Information.txt” 我的问题是第4步和第5步。我也不确定我点的菜是否正确。 代码如下所示 public static void deleteAcc
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!");
}
}
完整代码可在以下位置找到:
任何帮助都将不胜感激
我知道我没有正确地检查“帐户未找到”,并将在命名问题后尝试解决这个问题
提前谢谢 使用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请更详细地解释,您到底遇到了什么问题。有错误吗?然后您应该发布完整的堆栈跟踪。您应该在catch块中使用
e.printStackTrace()
。否则你会错过重要的信息。啊。我没有关闭我的br,我应该在关闭后放置我的重命名。非常感谢。