无法在Java中重命名和删除文件 [英] Unable to rename and delete file in Java

查看:285
本文介绍了无法在Java中重命名和删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NetBeans在Java中进行项目,我需要修改文件.因此,我将整个文件覆盖到另一个临时文件中,但是最后我无法重命名该临时文件或删除主文件.有解决方案吗?

I am doing a project in Java using NetBeans and I need to modify a file. So I overwrite the whole file in another temporary file, but at the end I could not rename the temporary file or delete the main file. Any solutions?

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);

推荐答案

我刚刚尝试了以下5条上面的项目行,并获得了预期的结果

I just tried 5 of the above project lines as below and got the desired result,

    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.

Employee_info.txt is getting deleted as well as temp.tmp is getting renamed as Employee_info.txt too.

此外,始终建议将删除/重命名的代码放在try/catch块中,如下所示:

Also, it is always recommended to put the code for delete/rename inside try/catch block like below:

 try{
        File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
        real.delete();
    }
    catch(IOException e){
        e.printstacktrace();
    }

请提供错误消息,以进一步帮助您.

Please provide the error message, to help you further.

这篇关于无法在Java中重命名和删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆