How do I move a file from one location to another in Java?

pmad picture pmad · Jan 10, 2011 · Viewed 191.9k times · Source

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?

Answer

Thilo picture Thilo · Jan 10, 2011
myFile.renameTo(new File("/the/new/place/newName.file"));

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

Renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: 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. The return value should always be checked to make sure that the rename operation was successful.

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile