Java IO & NIO - Files.move() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Method:

public static Path move(Path source,
                        Path target,
                        CopyOption... options)
                 throws IOException

Move or rename a file to a target file.

Parameters:
source - the path to the file to move
target - the path to the target file (may be associated with a different provider to the source path)
options - options specifying how the move should be done
Returns:
the path to the target file

Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class MoveExample {

public static void main(String... args) throws IOException {
Path fileToMovePath = Files.createTempFile(Files.createTempDirectory("testDir1"),
"test-file", ".txt");
System.out.println("File to move: " + fileToMovePath);
System.out.println("File to move exits: " + Files.exists(fileToMovePath));

Path destinationDir = Files.createTempDirectory("testDir2");
Path path = Files.move(fileToMovePath, destinationDir.resolve(fileToMovePath.getFileName()),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("File moved to: " + path);
System.out.println("File moved exits: " + Files.exists(path));
System.out.println("File to move exits: " + Files.exists(fileToMovePath));
}
}

Output

File to move: C:\Users\Joe\AppData\Local\Temp\testDir15191813571749764387\test-file14578421325077973575.txt
File to move exits: true
File moved to: C:\Users\Joe\AppData\Local\Temp\testDir27894271269449011530\test-file14578421325077973575.txt
File moved exits: true
File to move exits: false




Renaming a file

package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class MoveExample2 {

public static void main(String... args) throws IOException {
Path fileToRenamePath = Files.createTempFile(Files.createTempDirectory("testDir1"),
"test-file", ".txt");
System.out.println("File to rename: " + fileToRenamePath);
System.out.println("File to rename exits: " + Files.exists(fileToRenamePath));

Path path = Files.move(fileToRenamePath, fileToRenamePath.getParent().resolve("my-renamed-file.txt"),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("File renamed to: " + path);
System.out.println("File renamed exits: " + Files.exists(path));
System.out.println("File to rename exits: " + Files.exists(fileToRenamePath));
}
}

Output

File to rename: C:\Users\Joe\AppData\Local\Temp\testDir1139739613421181258\test-file16912921239565476269.txt
File to rename exits: true
File renamed to: C:\Users\Joe\AppData\Local\Temp\testDir1139739613421181258\my-renamed-file.txt
File renamed exits: true
File to rename exits: false




See Also