Domanda

I have the following code I've placed into a custom method.

File inputFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\original.txt");   // Your file  
File tempFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\temp.txt");// temp file
BufferedReader reader = null;
BufferedWriter writer = null;
try{
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(tempFile));

String firstName = chosenEmployee.getFirstName();
String lastName = chosenEmployee.getLastName();

String currentLine;

while((currentLine = reader.readLine()) != null) {

    if(currentLine.contains(firstName) 
         && currentLine.contains(lastName)) continue;

    writer.write(currentLine);
}
    }
    catch (IOException e) {
        e.printStackTrace();
        }finally{
            try {
                inputFile.delete();
                writer.close();
                boolean successful = tempFile.renameTo(inputFile);
                System.out.println(successful);
            } catch (IOException ex) {
               ex.printStackTrace();
            }

        }

The problem is; whenever I run the program the renameTo fails; but it does create a temp.txt with the line that was supposed to be removed correctly removed.

Why does renameTo always return false though?

Edit 1: The files are not opened anywhere else in windows. They are listed in my IDE's project explorer but are not opened by my IDE.

È stato utile?

Soluzione

The javadoc for renameTo() says:

The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists.

Try closing all the files (you are not closing reader so it is still "in use") and deleting first the input file:

} finally {
    try {
        inputFile.delete();
        reader.close();
        writer.close();
        inputFile.delete();
        boolean successful = tempFile.renameTo(inputFile);
        System.out.println(successful);
    } catch (IOException ex) {
           ex.printStackTrace();
    }

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top