Let us take a look at how to rename files in Java with examples of Java 7, 8, 9 and 11, and 17.
Example: Java 7package org.code2care.java.examples;
import java.io.File;
public class FileRenameJava7 {
public static void main(String[] args) {
File oldFileName = new File("old_file.csv");
File newFileName = new File("new_file.csv");
if (oldFileName.renameTo(newFileName)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename the file.");
}
}
}
Example: Java 8, 9 or 11
package org.code2care.java.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class FileRenameJava8 {
public static void main(String[] args) throws IOException {
Path oldFilePath = Path.of("old_file.csv");
Path newFilePath = Path.of("new_file.csv");
Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File renamed successfully.");
}
}
Example: Java 17
package org.code2care.java.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileRenameJava17 {
public static void main(String[] args) throws IOException {
Path oldFilePath = Path.of("old_file.csv");
Path newFilePath = Path.of("new_file.csv");
Path oldPath = Path.of("old.txt");
Path newPath = Path.of("new.txt");
Files.move(oldPath, newPath);
System.out.println("File renamed successfully.");
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!