Languages
[Edit]
EN

Java - rename or move file

0 points
Created by:
Huzaifa-Ball
415

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.

1. Rename file

In this example, we use Files.move() method to rename example.txt file to newName.txt.

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


public class Example {

    public static void main(String[] args) throws IOException {
        Path source = Paths.get("C:\\path\\example.txt");
        Path target = Paths.get("C:\\path\\newName.txt");

        try {
            
            Files.move(source, target);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Move file

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:

package tmpOperations;

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


public class Example {

    public static void main(String[] args) throws IOException {
        Path source = Paths.get("C:\\path\\example.txt");
        Path target = Paths.get("C:\\path\\newDirectory");

        // creates the target directory (no effect if directory exits)
        Files.createDirectories(target);

        Files.move(source, target.resolve(source.getFileName()),
                StandardCopyOption.REPLACE_EXISTING);
    }
}
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join