views:

137

answers:

4

I'm trying to use the renameTo method in Java but it just returns false and doesn't move the file.

Am I missing a step? Is there a way to find out why it's not moving the file? The delete method doesn't do anything either.

Here's my code showing how I'm using it:

private void archiveOutputFile(File outputFile) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssS");
    String timeStamp = formatter.format(new Date());
    String subFolderName = "Archive" + timeStamp;
    File subFolder = new File(outputFile.getParent(),subFolderName);
    subFolder.mkdir();
    File newFile = new File(subFolder,outputFile.getName());
    //outputFile.deleteOnExit(); //Doesn't work, nor does .delete()
    boolean success = outputFile.renameTo(newFile);
}

Here's some system info:

Java: 1.6.0_21; Java HotSpot(TM) Client VM 17.0-b17

System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)

+3  A: 

You cannot rename or delete a file which Windows consider to be open.

Thorbjørn Ravn Andersen
Turns out the Weka DataSource class I was sending the file to was somehow locking the file. I changed to use a constructor where I could send it an input stream instead of a file path and then closed the input stream myself. That ended up working.
Greg
It is enough that the file is opened and not closed yet.
Thorbjørn Ravn Andersen
A: 

I would recommend you to check for exists. public boolean exists()

More here

vodkhang
+1  A: 

You need to create the subfolder before you move the file into it (uncomment subFolder.mkdir();)

Maurice Perry
A: 

it works, if I comment in the line

subFolder.mkdir();
eldur
Well obviously, the problem was that the subfolder didn't exist. The `renameTo()` method won't create directories for you.
Stephen C
I tried it that way too with no luck. (I just updated the question.)
Greg