Método move() de Java java.nio.file.Files
java.nio.file.Files.move()El método es el método central del paquete Java NIO (New I/O) para mover o renombrar archivos y directorios. Proporciona, en comparación con las clases tradicionales,java.io.Fileuna capacidad de operación de archivos más potente y flexible.
Sintaxis del método
public static Path move(Path source, Path target, CopyOption... options) throws IOException
Descripción de parámetros
| Nombre del parámetro | Tipo | Descripción |
|---|---|---|
| source | Path | Ruta del archivo o directorio de origen a mover |
| target | Path | Ruta de la ubicación de destino |
| options | CopyOption... | Opciones de movimiento opcionales (argumentos variables) |
Opciones comunes de CopyOption
StandardCopyOption.REPLACE_EXISTING: si el archivo de destino ya existe, reemplázaloStandardCopyOption.ATOMIC_MOVE: asegura que la operación de movimiento sea atómicaLinkOption.NOFOLLOW_LINKS: no sigue enlaces simbólicos
Explicación detallada de la funcionalidad del método
Movimiento básico de archivos
La operación de movimiento más simple: mueve un archivo de una ubicación a otra:
Ejemplo
Path source = Paths.get("C:/temp/source.txt");
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target);
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target);
Renombrar archivos
El método move() también se puede utilizar para renombrar archivos:
Ejemplo
Path source = Paths.get("C:/temp/oldname.txt");
Path target = Paths.get("C:/temp/newname.txt");
Files.move(source, target);
Path target = Paths.get("C:/temp/newname.txt");
Files.move(source, target);
Movimiento de directorios
Mueve todo el directorio (incluido su contenido):
Ejemplo
Path sourceDir = Paths.get("C:/temp/mydir");
Path targetDir = Paths.get("C:/temp2/mydir");
Files.move(sourceDir, targetDir);
Path targetDir = Paths.get("C:/temp2/mydir");
Files.move(sourceDir, targetDir);
Uso avanzado
Sobrescribir archivos existentes
Usa laREPLACE_EXISTINGopción para sobrescribir el archivo de destino existente:
Ejemplo
Path source = Paths.get("C:/temp/source.txt");
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
Movimiento atómico
Asegura que la operación de movimiento sea atómica (o tiene éxito por completo, o falla por completo):
Ejemplo
Path source = Paths.get("C:/temp/source.txt");
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
Manejo de excepciones
move()El método puede lanzar las siguientes excepciones:
IOException: se lanza cuando ocurre un error de E/SFileAlreadyExistsException: el archivo de destino ya existe y no se especificó laREPLACE_EXISTINGopciónDirectoryNotEmptyException: se intenta mover un directorio no vacío a un sistema de archivos diferente
Forma recomendada de manejo de excepciones:
Ejemplo
try {
Path source = Paths.get("C:/temp/source.txt");
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.err.println(Error al mover el archivo: + e.getMessage());
e.printStackTrace();
}
Path source = Paths.get("C:/temp/source.txt");
Path target = Paths.get("C:/temp2/target.txt");
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.err.println(Error al mover el archivo: + e.getMessage());
e.printStackTrace();
}
Precauciones
- Movimiento entre sistemas de archivos: al mover archivos entre diferentes sistemas de archivos, en realidad es una operación de copiar + eliminar
- Enlaces simbólicos: por defecto se siguen los enlaces simbólicos, a menos que se especifique
LinkOption.NOFOLLOW_LINKS - Limitaciones del movimiento de directorios: no se puede mover un directorio a sí mismo ni a su subdirectorio
- Atributos de archivo: la operación de movimiento generalmente conserva los atributos básicos del archivo
- Consideraciones de rendimiento: mover dentro del mismo sistema de archivos suele ser mucho más rápido que mover entre sistemas de archivos
Ejemplos de aplicación práctica
Movimiento seguro de archivos
Ejemplo
public static boolean safeMoveFile(Path source, Path target) {
try {
// Intenta un movimiento atómico
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
return true;
} catch (AtomicMoveNotSupportedException e) {
try {
// Cuando el movimiento atómico no es compatible, usa movimiento normal + sobrescritura
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException ex) {
System.err.println(Error al mover el archivo: + ex.getMessage());
return false;
}
} catch (IOException e) {
System.err.println(Error al mover el archivo: + e.getMessage());
return false;
}
}
try {
// Intenta un movimiento atómico
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
return true;
} catch (AtomicMoveNotSupportedException e) {
try {
// Cuando el movimiento atómico no es compatible, usa movimiento normal + sobrescritura
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException ex) {
System.err.println(Error al mover el archivo: + ex.getMessage());
return false;
}
} catch (IOException e) {
System.err.println(Error al mover el archivo: + e.getMessage());
return false;
}
}
Movimiento masivo de archivos
Ejemplo
public static void batchMoveFiles(Path sourceDir, Path targetDir, String filePattern)
throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(sourceDir, filePattern)) {
for (Path sourceFile : stream) {
Path targetFile = targetDir.resolve(sourceFile.getFileName());
Files.move(sourceFile, targetFile);
}
}
}
throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(sourceDir, filePattern)) {
for (Path sourceFile : stream) {
Path targetFile = targetDir.resolve(sourceFile.getFileName());
Files.move(sourceFile, targetFile);
}
}
}
Java java.nio.file.Files