我正在使用NetBeans进行Java项目,我需要修改文件。所以我在另一个临时文件中覆盖整个文件,但最后我无法重命名临时文件或删除主文件。任何解决方案?
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
FileReader fr = new FileReader("F:\\nb\\project_inventory\\Employee_info.txt");
BufferedReader br =new BufferedReader(fr);
FileWriter fw = new FileWriter(tf);
PrintWriter bw =new PrintWriter(fw);
String line;
while((line=br.readLine())!=null)
{
if(line.contains(del_id)) continue;
bw.println(line);
}
bw.close();
fw.close();
br.close();
fr.close();
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
tf.renameTo(real);
答案 0 :(得分:1)
我刚刚尝试了以上5个项目行,得到了理想的结果,
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
try{
tf.createNewFile(); // for creating the new file
}
catch(IOException e){
e.printstacktrace();
}
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
tf.renameTo(real);
Employee_info.txt被删除,temp.tmp也被重命名为Employee_info.txt。
此外,总是建议将删除/重命名代码放在try / catch块中,如下所示:
try{
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
}
catch(IOException e){
e.printstacktrace();
}
请提供错误消息,以便进一步帮助您。