¿Cómo puedo mover un archivo de una ubicación a otra en Java?


¿Cómo se mueve un archivo de una ubicación a otra? Cuando corro mi programa, cualquier archivo creado en esa ubicación se mueve automáticamente a la ubicación especificada. ¿Cómo sé qué archivo se mueve?

Gracias de antemano!

Author: Sam1370, 2011-01-10

10 answers

myFile.renameTo(new File("/the/new/place/newName.file"));

File # renameTo hace eso (no solo puede renombrar, sino también moverse entre directorios, al menos en el mismo sistema de archivos).

Cambia el nombre del archivo indicado por esta ruta abstracta.

Muchos aspectos del comportamiento de este método dependen inherentemente de la plataforma: La operación de cambio de nombre podría no ser capaz de mover un archivo de un sistema de archivos a otro, podría no ser atómica, y podría no tener éxito si un archivo con la ruta abstracta de destino ya existe. El valor devuelto siempre se debe verificar para asegurarse de que la operación de cambio de nombre se realizó correctamente.

Si necesita una solución más completa (como querer mover el archivo entre discos), mire Apache Commons FileUtils#MoveFile

 83
Author: Thilo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-10 12:32:50

Con Java 7 o posterior puede usar Files.move(from, to, CopyOption... options).

Por ejemplo

Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);

Vea la documentación de Files para más detalles

 50
Author: micha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-15 09:52:49

Para mover un archivo también puede usar Jakarta Commons iOS FileUtils.MoveFile

En caso de error, lanza un IOException, por lo que cuando no se lanza ninguna excepción, sabe que el archivo se movió.

 5
Author: DerMike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-10 09:30:42

File.renameTo desde Java IO se puede utilizar para mover un archivo en Java. También vea esta pregunta.

 4
Author: Piotr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:05

Simplemente agregue las rutas de las carpetas de origen y destino.

Moverá todos los archivos y carpetas de la carpeta de origen a carpeta de destino.

    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");
    }
 3
Author: manjeet lama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 13:48:47

Podría ejecutar una herramienta externa para esa tarea (como copy en entornos windows) pero, para mantener el código portable, el enfoque general es:

  1. leer el archivo fuente en la memoria
  2. escriba el contenido en un archivo en la nueva ubicación
  3. eliminar el archivo fuente

File#renameTo funcionará siempre y cuando la ubicación de origen y destino estén en el mismo volumen. Personalmente evitaría usarlo para mover archivos a diferentes carpetas.

 2
Author: Andreas_D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-10 09:28:51

Prueba esto: -

  boolean success = file.renameTo(new File(Destdir, file.getName()));
 2
Author: Vijay Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-08 04:01:44

Java 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

    return fileToMove.renameTo(new File(targetPath));
}

Java 7 (Usando NIO)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean flag = true;

    try {

        Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);

    } catch (Exception e) {

        flag = false;
        e.printStackTrace();
    }

    return flag;
}
 1
Author: Pranav V R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-27 17:44:28
Files.move(source, target, REPLACE_EXISTING);

Puede usar el objeto Files

Leer más sobre Archivos

 0
Author: Daniel Taub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-10 13:08:14

Escribió este método para hacer esto mismo en mi propio proyecto solo con el archivo de reemplazo si la lógica existente en él.

// 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;
    }       
}
 0
Author: Joel M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-08 15:47:16