Deleting and Renaming File in Java Programming

I need help in in deleting and then renaming the file in Java programming. My problem is the original file cannot be deleted and second file cannot be renamed. Here is the snippet code. Any suggestion would be appreciated.

import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;




public void deleteLine(String content) {
    try {

        File inFile = new File("football.dat");
        if (!inFile.isFile()) {
            System.out.println("Parameter is not an existing file");
            return;
        }
        File tempFile = new File(inFile.getAbsolutePath() + "2");
        BufferedReader br = new BufferedReader(new FileReader(inFile));
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile), true);

        String linetobeempty = null;
        while ((linetobeempty = br.readLine()) != null) {

            if (!linetobeempty.trim().equals(content)) {
                pw.println(linetobeempty);
                pw.flush(); System.out.println(linetobeempty);
            }
        }

        pw.close();        
        br.close();
       boolean b = inFile.delete();

        if (!b) {
            System.out.println("Could not delete file");
            return;
        }

        //Rename the new file to the filename the original file had.
        if (!tempFile.renameTo(inFile)) {
            System.out.println("Could not rename file");
        }


    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Upvotes: 0

Views: 789

Answers (2)

j13r
j13r

Reputation: 2671

Are you on Windows? On Windows, unlink and rename fail if any process has a file handle on the file (unlike UNIX). I have even noticed that sometimes you need to give the OS a break between the writing of a file and it's deletion when doing file I/O testing in Java. The doc on renameTo and delete give some limited insight.

To simplify your problem and debug it better, just create the file instead of writing to it -- use File.createNewFile().

Possibly you have the same issue as Cannot delete file Java .

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200138

There is nothing in this code snippet that would be the direct cause of the file not getting deleted. The problem lies deeper down -- permissions, open by some other process, the usual stuff. Check all that. Of course, the reason why renaming fails after the failed delete is obvious, so currently you have only one problem that you know about.

Upvotes: 1

Related Questions