Unable to rename and delete file in Java

前端 未结 1 765
感动是毒
感动是毒 2021-01-27 06:19

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

相关标签:
1条回答
  • 2021-01-27 06:27

    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 is getting deleted as well as temp.tmp is getting renamed as Employee_info.txt too.

    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.

    0 讨论(0)
提交回复
热议问题