130

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?

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
pmad
  • 1,537
  • 3
  • 17
  • 20
  • 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 Answers11

169
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

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 9
    myFile.renameTo(new File("/the/new/place/newname.file")); – djangofan Sep 01 '11 at 23:56
  • 4
    Yes, do not just give the new parent directory. And make sure the path there already exists. – Thilo Sep 02 '11 at 00:14
  • 4
    Note 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
  • Use File.separator instead of a slash. Just submitted an edit. – sam1370 Jun 20 '18 at 01:49
  • 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
89

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

Saurabh Gour
  • 643
  • 2
  • 8
  • 24
micha
  • 47,774
  • 16
  • 73
  • 80
12

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;
}
pvrforpranavvr
  • 2,708
  • 2
  • 24
  • 34
7

File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.

Community
  • 1
  • 1
Piotr
  • 5,543
  • 1
  • 31
  • 37
5

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");
    }
Umesh Sulakude
  • 286
  • 2
  • 14
manjeet lama
  • 185
  • 3
  • 12
5

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.

DerMike
  • 15,594
  • 13
  • 50
  • 63
3
Files.move(source, target, REPLACE_EXISTING);

You can use the Files object

Read more about Files

Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
2

Try this :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));
Vijay
  • 4,694
  • 1
  • 30
  • 38
2

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:

  1. read the source file into memory
  2. write the content to a file at the new location
  3. 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.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

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;
    }       
}
Joel M
  • 1
0

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;
            }
Saranga kapilarathna
  • 564
  • 1
  • 12
  • 25