Java File IO 类

File type

Construction method

  As most basic operation IO classes, class File folders and files can be encapsulated, configured as follows:

1, create a new File instance by the given parent abstract pathname and a child pathname string.

File(File parent, String child);

2, by converting the given pathname string into an abstract pathname to create a new instance of File.

File(String pathname) 

3, create a new File instance from a parent pathname string and a child pathname string.

File(String parent, String child) 

4, by the given file: URI converted into an abstract pathname to create a new File instance.

File(URI uri) 

The following is a demonstration of the constructor:

public static void main(String[] args)
    {
        /**
            File类的构造函数
            如何创建文件对象
        **/
        String pathname = "D:\\forio";
        String pathname2 = "D:\\forio\\3.txt";  //封装的是3.txt这个文件
        File f1 = new File(pathname);   //将forio文件夹封装成对象,注意也可以封装不存在的文件或者文件夹,变成对象,可以再创建嘛
        System.out.println(f1);


        File f2 = new File("D:\\forio","3.txt");//分开之后可以将后面的变成一个变量
        System.out.println(f2);

        File dir = new File("D:\\forio");
        File f3 = new File(dir,"3.txt");
        System.out.println(f3);

        //也可以像下面这样,File.separator表示系统分隔符,可以适应所有系统,不止Windows
        File f4 = new File("D:"+File.separator+"forio"+File.separator+"3.txt");
        System.out.println(f4);
    }

Method of operating a file

After the successful creation of the object can call the methods of the class to manipulate files or folders, more of these methods is not listed, you can go check the documents, here are some of the more commonly used method.
1, to obtain basic information

public static void main(String[] args)
{
    /*
      File类的方法演示
      获取文件的信息,名称,大小,时间
    */
    File file = new File("D://forio//3.txt");

    String absPath = file.getAbsolutePath();    //绝对路径
    String pathString= file.getPath();   //File中封装的路径是什么获取的就是什么
    String filename = file.getName();
    long size = file.length();          //字节数
    long time = file.lastModified();    //毫秒值

    System.out.println("absPath="+absPath);
    System.out.println("Path="+pathString);
    System.out.println("filename="+filename);
    System.out.println("size="+size);
    System.out.println("time="+time);

    //毫秒值--Date--格式化--字符串文本
    String str_date = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG).format(new Date(time));
    System.out.println(str_date);
}

2, create, delete, exists
for folders and files as well as create and delete operations, as well as to determine whether a directory exists.

To the folder: File dir = new File("D:\\demo");  File dirs = new File("D:\\haha\\hehe\\xixi");

  • Create a single-folder: dir.mkdir ();
  • Create multiple folders: dirs.mkdirs ();
  • Delete the folder: dir.delete (); dirs.delete (); if there is content in the folder, you need to delete the content, and then the folder to delete
  • It determines whether there is: dir.exists ();

To file:File file = new File("D:\\forio\\3.txt");

  • Create a file: file.createNewFile ();
  • Delete files: file.delete ();
  • Analyzing the presence of: file.exists ();

 Above the return value is boolean type, or the existence of a successful return True, otherwise False

  • Create a file, if the file does not exist, create returns true
  • If there is, do not create, returns false
  • If the path is wrong, IOException
  • Return false when deleting two situations: 1, does not exist, 2, is being used

3, ListFile methods include the entire contents of the directory

ListFile method return value is an array of File objects, the storage of all files in the directory and folder objects

import java.io.File;

public class ListFiles {
    public static void main(String[] args)
    {
        //需求:对给定的目录获取内部的内容
        File dir = new File("D:\\forio");
        //判断:1、必须是存在的   2、必须是目录,否则容易引发空指针异常NullPointerException

        String[] names = dir.list();    //获取的是目录下的当前的文件以及文件夹名称
        for (String name : names) {
            //  System.out.println(name);
        }


        File[]files = dir.listFiles();  //获取目录下的当前文件以及文件夹对象
        for (File file : files) {
            System.out.println(file.getName());
        }
    }
}

4, the filter

Filter filter file name, to achieve FilenameFilter interface and override the accept method, if the file name in accordance with pre-set rules, returns True, otherwise False

public class FilenameFilterByTxt implements FilenameFilter {
    private String suffix;

    //构造函数
    public FilenameFilterByTxt(String s){
        suffix = s;
    }

    //重写accept函数
    @Override
    public boolean accept(File file, String name) {
        return name.endsWith(suffix);   //也可以直接endwith(".txt"); 但这样可以减少耦合性,更灵活的选择以哪种结束
    }
}
public class FileDemo {
    public static void main(String[] args)
    {
        //需求:获取目录中的文件,只要.txt文件

        File dir = new File("D:\\forio");

        File[] files = dir.listFiles(new FilenameFilterByTxt(".txt"));      //传入过滤器,如果懵逼了可以查看listFiles的API

        /*  listFiles方法的源码:
         *
         * public File[] listFiles(FilenameFilter filter)
         * {
                String ss[] = list();       //调用File类中的list方法,先获取所有的名称
                if (ss == null) return null;    //判断,如果数组为空,返回
                ArrayList<File> files = new ArrayList<>();  //创建了一个集合,元素是File类型
                for (String s : ss)             //遍历数组名称

                //调用accept方法,对遍历的名称进行过滤器判断,将当前目录this,遍历到名称s传递给accept方法,如果过滤器为空,即没有过滤条件。则全部为真
                    if ((filter == null) || filter.accept(this, s))
                        files.add(new File(s, this));   //将满足过滤条件的添加到集合中,将名称和当前目录封装成File对象。new File(dir,name);
                return files.toArray(new File[files.size()]);   //将集合转成数组返回,因为不需要增删操作
            }
         * */


        for (File file : files) {
            System.out.println(file);
        }
    }
}

Filters folder, and different iterators above, less a private member, accept less a function parameter is actually overloaded to accept function

public class FileFilterByDir implements FileFilter {

    @Override
    public boolean accept(File pathname) {
        // TODO Auto-generated method stub
        return pathname.isDirectory();
    }
}
import java.io.File;
import java.io.FileFilter;

public class Demo 
{
    public static void main(String[] args) 
    {
        File dir = new File("D:\\forio");
        /*
    public File[] listFiles(FileFilter filter) {
        String[] ss = this.list();
        if (ss == null) {
            return null;
        } else {
            ArrayList<File> files = new ArrayList();
            String[] var4 = ss;
            int var5 = ss.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String s = var4[var6];
                File f = new File(s, this);
                if (filter == null || filter.accept(f)) {
                    files.add(f);
                }
            }
        */
        File[] files = dir.listFiles(new FileFilterByDir());//传入过滤器,如果懵逼了可以查看listFiles的API
        for (File file : files) {
            System.out.println(file);
        }
    }
}

Exercise

1, access to all the contents of the directory because a file folder may contain files may also contain folders, so you need to use recursion, using a global variable statistical number.

public class exercise1 {

    static int acount=0;    //统计数目
    public static void main(String[] args)
    {
        /***
         * File类的listFiles()列出当前目录下的文件以及文件夹内容
         *
         * 需求:能不能列出当前目录下的子目录中的所有内容
         * 思路:
         *  1、在遍历当前目录时,会获取到当前的所有文件及文件夹
         *  2、要遍历子目录需要对获取的当前的file对象进行判断,只有是目录时才可以作为子目录进行继续遍历
         */

        File dirFile = new File("D:\\VS 2019");
        ListAll(dirFile);
        System.out.println("一共有"+acount+"个文件和文件夹");
    }

    public static void ListAll(File dir)    //dir用来接收待遍历的目录
    {
        File[] files = dir.listFiles();

        for (File file2 : files) {
            if(file2.isDirectory())     //如果遍历到当前的file对象是个目录,继续遍历,递归调用
            {
                ListAll(file2);
            }
            acount++;
            System.out.println(file2.getName());
        }
    }
}

2, do not use recursion to get all subdirectories under a directory, since it does not use recursion, it would need to consider the breadth-first search, will join a queue directory, then copy the files directly to the output file name, and then the first team subdirectory continue its traverse, repeat the above operation, you can get the entire contents.

public class exercise2 {

    static int acount=0;
    public static void main(String[] args)
    {
        /*
         * 遍历文件夹,且不使用递归:
         * 思路:
         *  1、遍历test目录,将子目录存储到容器内
         *  2、遍历容器。从容器中取出子目录,进行遍历
         *  3、子目录中还有目录,继续存储,让遍历过的容器中的目录出队,释放容器空间
         *  4、容器大小不确定,所以用集合
         *  5、目录名有可能重复,所以用队列
         */


        File dir = new File("D:\\C++");

        Queue<File> queue = new Queue<File>();
        //1、对dir进行当前目录的遍历
        File[]files = dir.listFiles();
        for (File file : files)
        {
            //2、如果有子目录,存储到队列中
            if(file.isDirectory())
            {
                acount++;
                queue.myAdd(file);
            }
            else
            {
                acount++;
                System.out.println(file.getName());
            }
        }
        //3、遍历队列容器。因为子目录都在队列中
        while(!queue.IsEmpty())
        {
            File[] files2 = queue.myRemove().listFiles();
            for (File file : files2) {
                if(file.isDirectory())
                {
                    acount++;
                    queue.myAdd(file);
                }
                else {
                    System.out.println(file.getName());
                    acount++;
                }
            }
        }
        System.out.println("一共有"+acount+"个文件");
    }
}

class Queue<E>
{
    private LinkedList<E> link;
    public Queue()
    {
        link = new LinkedList<E>();
    }
    public void myAdd(E obj)
    {
        link.addFirst(obj);
    }
    public E myRemove()
    {
        return  link.removeLast();
    }
    public boolean IsEmpty()
    {
        return link.isEmpty();
    }
}

Guess you like

Origin www.cnblogs.com/vfdxvffd/p/11694086.html