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?
-
First you ask about how to move one file, then you say that some files are automatically being moved. Can you make your question more clear?. – Jaime Hablutzel Nov 19 '19 at 14:13
11 Answers
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
-
9
-
4Yes, do not just give the new parent directory. And make sure the path there already exists. – Thilo Sep 02 '11 at 00:14
-
4Note that the object `myFile`'s path is not updated by this command. So it will be pointing to a file that is no longer there. – Evgeni Sergeev Dec 12 '14 at 09:15
-
1@Sulemankhan - yes, it also deletes the file. It really moves it on the file system – leole May 03 '16 at 07:44
-
Make sure the `File` is not locked (e.g. already open) otherwise it will not be moved. – Julien Kronegg Mar 07 '18 at 22:25
-
2@JulienKronegg: That probably depends on your OS/filesystem. I think in Linux you can move (or delete) files that are currently open (and continue to access them through the existing file handle), but not on Windows. – Thilo Mar 08 '18 at 05:34
-
-
You need to be careful when using renameTo. If there is not enough space it doesn't throw an exception, just to give an example. – Johan Durán Jan 26 '22 at 17:00
With Java 7 or newer you can use Files.move(from, to, CopyOption... options)
.
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details

- 643
- 2
- 8
- 24

- 47,774
- 16
- 73
- 80
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}

- 2,708
- 2
- 24
- 34
Just add the source and destination folder paths.
It will move all the files and folder from source folder to destination folder.
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}

- 286
- 2
- 14

- 185
- 3
- 12
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException
, so when no exception is thrown you know that that the file was moved.

- 15,594
- 13
- 50
- 63

- 5,133
- 7
- 42
- 72
-
1
-
After moving all files from source to destination it'll delete source directory as well @Daniel Taub – Deep Dalsania Sep 13 '21 at 07:37
Try this :-
boolean success = file.renameTo(new File(Destdir, file.getName()));

- 4,694
- 1
- 30
- 38
You could execute an external tool for that task (like copy
in windows environments) but, to keep the code portable, the general approach is to:
- read the source file into memory
- write the content to a file at the new location
- delete the source file
File#renameTo
will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.

- 113,398
- 19
- 180
- 268
-
@BullyWiiPlaza: read the big disclaimer in Thilo's answer. It's broken in many ways on some platforms (e.g. Windows). – AndrewBourgeois Oct 12 '15 at 10:54
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}

- 1
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}

- 564
- 1
- 12
- 25
-
1This would be more robust if the `close` instructions were in a `finally` block, or if it used a try-with-resources block. – MikaelF Mar 06 '20 at 06:09
-