File类

1    IO概述

当需要把内存中的数据存储到持久化设备上这个动作称为输出(写)Output操作。

当把持久设备上的数据读取到内存中的这个动作称为输入(读)Input操作。

因此我们把这种输入和输出动作称为IO操作。

File方法:

public class File02 {
    public static void main(String[] args) throws IOException {
        m1();
    }
    public static void m1(){
        //相对路径:相对本工程的路径
        File file=new File("src");
        //获取绝对路径
        System.out.println(file.getAbsolutePath());
        //获取文件名
        System.out.println(file.getName());
        //获取字符串路径
        System.out.println(file.getPath());
        //获取该文件的长度
        System.out.println(file.length());
    }
    public static void m2() throws IOException{
        File file=new File("D:\\test\\c.JaVa");
        //新建文件
        //不能创建同名文件
        //不能创建文件夹
        boolean flag=file.createNewFile();
        System.out.println(flag);
    }
    public static void m3(){
        File file=new File("D:\\test\\e");
        //创建文件夹
        boolean flag =file.mkdir();
        //创建多级  mkdirs();        
        System.out.println(flag);
    }
    public static void m4(){
        File file=new File("D:\\test\\a.txt");
        //判断该file指定的文件(夹)是否存在
        System.out.println(file.exists());
        //判断该file指定的文件(夹)是否是目录
        System.out.println(file.isDirectory());
        //判断该file指定的文件(夹)是否是文件
        System.out.println(file.isFile());
        //删除文件(夹)
        boolean flag=file.delete();
        System.out.println(flag);
    }
    public static void m5(){
        File file =new File("D:\\test");
        String[] files=file.list();
        for(String f:files){
            System.out.println(f);
        }
    }
    public static void m6(){
        File file =new File("D:\\test");
        File[] files=file.listFiles();
        for(File f:files){
            System.out.println(f);
        }
    }
}
public class FileDemo01 {
    public static void main(String[] args) {
        //File:文件
        //directory:目录(文件夹)
        //path:路径
        File file=new File("D:\\test\\b.txt"); 
        //File类的构造方法没有检测该路径指定的文件是否存在的功能
        System.out.println(file.exists());
    }
    public static void m1(String parent,String child){
        File file=new File(parent,child);
        System.out.println(file);
    }
    public static void m2(File parent,String child){
        File file=new File(parent,child);
        System.out.println(file);
    }
}

 

2     文件过滤器

FileFilter接口,

 自定类继承FileFilter过滤器接口

public class MyFileFilter implements FileFilter{
    public boolean accept(File pathname){
        return pathname.getName().toLowerCase().endsWith(".java");
    }
}

然后筛选符合条件的文件

public class File03 {
    public static void main(String[] args) {
        File file=new File("D:\\test");
        File[]files=file.listFiles(new MyFileFilter());
        for(File f:files){
            System.out.println(f);
        }    
    }
}

 

posted @ 2019-04-03 17:26  一叶之_秋  阅读(125)  评论(0编辑  收藏  举报