在java编程中,如何重命名文件?
此示例演示如何使用File
类的oldName.rename To(new_Name)
方法重命名文件。
package com.yiibai;
import java.io.File;
public class RenameFile {
public static void main(String[] args) {
File oldName = new File("F:/worksp/javaexamples/java_files/demo1.txt");
File newName = new File("F:/worksp/javaexamples/java_files/demo1-new.txt");
if (oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
}
执行上述示例代码,将产生以下结果 -
renamed
示例-2
以下是java中重命名文件的另一个示例:
package com.yiibai;
import java.io.File;
public class RenameFile2 {
public static void main(String[] args) {
File oldfile = new File("F:/worksp/javaexamples/java_files/oldfile_name.txt");
File newfile = new File("F:/worksp/javaexamples/java_files/newfile_name.txt");
if (oldfile.renameTo(newfile)) {
System.out.println("File name changed succesful");
} else {
System.out.println("Rename failed");
}
}
}
执行上述示例代码,将产生以下结果 -
File name changed succesful