EN
Java - rename or move file
0 points
In this article, we would like to show you how to rename or move file in Java.
We use Files.move()
method both to rename or move a file to a target file.
In this example, we use Files.move()
method to rename example.txt
file to newName.txt
.
xxxxxxxxxx
1
import java.io.IOException;
2
import java.nio.file.Files;
3
import java.nio.file.Path;
4
import java.nio.file.Paths;
5
6
7
public class Example {
8
9
public static void main(String[] args) throws IOException {
10
Path source = Paths.get("C:\\path\\example.txt");
11
Path target = Paths.get("C:\\path\\newName.txt");
12
13
try {
14
15
Files.move(source, target);
16
17
} catch (IOException e) {
18
e.printStackTrace();
19
}
20
}
21
}
In this example, we use:
Files.createDirectories
- to create the directory if doesn't exist,Files.move
- to move the file under specified path (source
) to the new directory (target
).
Practical example:
xxxxxxxxxx
1
package tmpOperations;
2
3
import java.io.IOException;
4
import java.nio.file.Files;
5
import java.nio.file.Path;
6
import java.nio.file.Paths;
7
import java.nio.file.StandardCopyOption;
8
9
10
public class Example {
11
12
public static void main(String[] args) throws IOException {
13
Path source = Paths.get("C:\\path\\example.txt");
14
Path target = Paths.get("C:\\path\\newDirectory");
15
16
// creates the target directory (no effect if directory exits)
17
Files.createDirectories(target);
18
19
Files.move(source, target.resolve(source.getFileName()),
20
StandardCopyOption.REPLACE_EXISTING);
21
}
22
}