Moving a File or Directory
You can move a file or directory by using the move(Path, Path, CopyOption. ) method. The move fails if the target file exists, unless the REPLACE_EXISTING option is specified.
Empty directories can be moved. If the directory is not empty, the move is allowed when the directory can be moved without moving the contents of that directory. On UNIX systems, moving a directory within the same partition generally consists of renaming the directory. In that situation, this method works even when the directory contains files.
This method takes a varargs argument – the following StandardCopyOption enums are supported:
- REPLACE_EXISTING – Performs the move even when the target file already exists. If the target is a symbolic link, the symbolic link is replaced but what it points to is not affected.
- ATOMIC_MOVE – Performs the move as an atomic file operation. If the file system does not support an atomic move, an exception is thrown. With an ATOMIC_MOVE you can move a file into a directory and be guaranteed that any process watching the directory accesses a complete file.
The following shows how to use the move method:
import static java.nio.file.StandardCopyOption.*; . Files.move(source, target, REPLACE_EXISTING);
Though you can implement the move method on a single directory as shown, the method is most often used with the file tree recursion mechanism. For more information, see Walking the File Tree.
Previous page: Copying a File or Directory
Next page: Managing Metadata (File and File Store Attributes)
Перемещение файла из одного каталога в другой в Java
Мы можем использовать API Files.move() для перемещения файлов из одного каталога в другой в Java. Ниже приведен синтаксис метода перемещения.
public static Path move(Path source,Path target,CopyOption. options) throws IOException
- source – исходный путь файла, который будет перемещен;
- target – целевой путь файла для перемещения;
- параметры – такие параметры, как REPLACE_EXISTING, ATOMIC_MOVE.
Пример перемещения
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Tester < public static void main(String[] args) < //move file from D:/temp/test.txt to D:/temp1/test.txt //make sure that temp1 folder exists moveFile("D:/temp/test.txt", "D:/temp1/test.txt"); >private static void moveFile(String src, String dest ) < Path result = null; try < result = Files.move(Paths.get(src), Paths.get(dest)); >catch (IOException e) < System.out.println("Exception while moving file: " + e.getMessage()); >if(result != null) < System.out.println("File moved successfully."); >else < System.out.println("File movement failed."); >> >
Итог
Средняя оценка 5 / 5. Количество голосов: 1
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Видим, что вы не нашли ответ на свой вопрос.
Напишите комментарий, что можно добавить к статье, какой информации не хватает.