File是文件和目录路径名的抽象表示形式。 File提供了许多方法可以让我们对文件及目录进行操作,需要注意的是:File 类的实例是不可变的;也就是说,一旦创建,File 对象表示的抽象路径名将永不改变。
文件对象的创建
文件对象的构造方法:
文件及目录的新增、删除
public static void tes()throws Exception{
File file1 = new File("e:/file/test");
File file2 = new File(file1,"test.txt");
System.out.println("目录是否存在:"+file1.exists());
if(!file1.exists()){
System.out.println("创建目录");
file1.mkdirs();
}
System.out.println("目录是否存在:"+file1.exists());
System.out.println("文件是否存在:"+file2.exists());
if(!file2.exists()){
System.out.println("创建文件");
file2.createNewFile();
}
System.out.println("文件是否存在:"+file2.exists());
System.out.println("删除文件");
file2.delete();
System.out.println("文件是否存在:"+file2.exists());
System.out.println("删除目录");
file1.delete();
System.out.println("目录是否存在:"+file1.exists());
File.createTempFile("temp",".doc").delete();
File.createTempFile("test",".doc",file).delete();
}
3 获取文件属性
public static void test1()throws IOException{
File file = new File("e:/io/file");
if(!file.exists()){
file.mkdirs();
}
File file1 = new File("e:/io/file/test.txt");
System.out.println(file1.createNewFile());
System.out.println(file1.canExecute());
System.out.println(file1.canRead());
System.out.println(file1.canWrite());
System.out.println(file.compareTo(file));
System.out.println(file1.compareTo(file));
System.out.println(file.compareTo(file1));
File file2 = file1.getAbsoluteFile();
String path = file1.getCanonicalPath();
File file3 = new File("/update");
System.out.println(file3.getAbsolutePath());
File file4 = file3.getCanonicalFile();
System.out.println(file4);
String path1 = file3.getCanonicalPath();
System.out.println(path1);
System.out.println(file3.getFreeSpace());
System.out.println(file3.getTotalSpace());
System.out.println(file3.getUsableSpace());
System.out.println("******************");
System.out.println(file3.getName());
System.out.println(file3.getParent());
System.out.println(file3.getParentFile());
System.out.println(file3.getPath());
System.out.println(file3.isAbsolute());
System.out.println(file1.isAbsolute());
System.out.println(file2.isDirectory());
System.out.println(file.isDirectory());
System.out.println(file4.isFile());
System.out.println(file.isHidden());
System.out.println(file.lastModified());
System.out.println(file1.length());
System.out.println("********************");
File file5 = new File("e:/io/file/rename.doc");
file1.renameTo(file5);
}
4 遍历目录中所有文件
public static void test4(){
File file = new File("c:/");
test5(file);
}
public static void test5(File file){
File[] files = file.listFiles();
if(files != null) {
for (File file1 : files) {
if (file1.isDirectory()) {
test5(file1);
} else {
System.out.println(file1.getAbsolutePath()+"隐藏:"+file1.isHidden());
}
}
}
}
源码:
https://github.com/wolf521/demo/tree/master/src/main/java/com/example/demo/io