File类
file在创建对象时,不能创建文件夹和文件,只是对文件的一个描述
对文件的创建,构造方法:
public static void test1(){
File file =new File("D:\\a\\b\\a.txt");
//只是创建了,但是不存在
File file1 =new File("D:\\a\\b","a.txt");
File path=new File("D:\\a\\b");
File file2=new File(path,"a.txt");
System.out.println(file+","+file1+","+file2);
}
测试文件夹的创建,在规定的位置处:
//测试文件夹的创建与删除
public static void test2(){
File file =new File("D:\\a");
if(!file.exists()){
boolean b=file.mkdir();
System.out.println("创建:"+b);
}else{
boolean b=file.delete();
System.out.println("删除:"+b);
}
}
//创建多个路径下的文件夹
public static void test21(){
File file =new File("D:\\a\\b\\c");
if(!file.exists()){
boolean b=file.mkdirs();
//mkdirs创建多个文件夹
System.out.println("创建:"+b);
}else{
//只能删除掉最后一层上面的文件夹
boolean b=file.delete();
System.out.println("删除:"+b);
}
}
创建文件:
//创建文件
public static void test3() throws IOException{
File file =new File("a.txt");
if(!file.exists()){
boolean b=file.createNewFile();
System.out.println("创建:"+b);
}
}
file类的常用方法:
//常用方法
public static void test4(){
File file = new File("a.txt");
System.out.println(file.isFile());
System.out.println(file.isDirectory());//判断路径
System.out.println(file.getName());//
System.out.println(file.getParent());
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());//绝对路径
System.out.println(file.length());
}