Sazzad
Sazzad

Reputation: 17

Unable to rename and delete file in 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);

Upvotes: 0

Views: 973

Answers (1)

dildeepak
dildeepak

Reputation: 1389

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.

Upvotes: 1

Related Questions