import java.io.File;
public class File_2_OperateDemo {
public static void main(String[] argv) throws Exception {
//创建文件。默认在应用程序根目录下生成test.txt文件,若文件已生成不会覆盖
File dummyFile = new File("test.txt");
boolean fileCreated = dummyFile.createNewFile();
System.out.print("\r\n 文件生成结果:" + fileCreated + ";文件生成路径:" + dummyFile.getAbsolutePath());
//创建临时文件。创建临时文件用于文件路径权限敏感的情况
File tempFile = File.createTempFile("abc", ".txt");
System.out.print("\r\n 文件生成路径:" + tempFile.getAbsolutePath());
//创建文件路径。
File newDir = new File("C:\\test");
boolean dirCreated = newDir.mkdir();
System.out.print("\r\n 文件路径创建结果:" + dirCreated);
//文件重命名。
File oldFile = new File("old_dummy.txt");
File newFile = new File("new_dummy.txt");
boolean fileRenamed = oldFile.renameTo(newFile);
if (fileRenamed) {
System.out.println("\r\n 文件重命名结果:" + oldFile + " renamed to " + newFile + " success.");
} else {
System.out.println("\r\n 文件重命名结果: Renaming " + oldFile + " to " + newFile + " failed.");
}
//文件重命名,文件必须真实存在。
fileCreated = oldFile.createNewFile();
if (fileCreated || oldFile.exists()) {
//若目标文件已经存在,则重命名不会成功,所以若存在需要先删除。
if (newFile.exists()) newFile.delete();
boolean renamedFlag = oldFile.renameTo(newFile);
if (!renamedFlag) {
System.out.println("Could not rename " + oldFile);
}
System.out.println("\r\n 文件重命名结果: Renaming " + oldFile + " to " + newFile
+ " success.");
}
//获取文件长度。length()方法(以字节为单位),如果File对象表示不存在的文件,则length()方法返回零
File myFile = new File("myfile.txt");
long fileLength = myFile.length();
System.out.println("\r\n 文件长度: " + fileLength);
}
}
参考: