Java Basics (three) | IO streams using the File class correct posture

File

To prepare for the interview quit, we began to enter the Java-based review today. I hope good foundation students reading this article, can grasp the generics, but when the right to review the basis of good students, I hope after reading this article you can play a little Sentimental memories.

First, what is the File class?

java.io.File class is an abstract file and directory path names indicate, mainly used to create files and directories, find and delete files.

Second, use the File class

2.1 Constructor

There are three class configuration File:

  • public File(String pathname): Direct string created by the file path
  • public File(String parent, String child): String path created by the parent and child
  • public File(File parent, String child): Create a parent file object, combined to create sub-path
/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.file <br/>
 * Date:2020/1/3 22:22 <br/>
 *
 * @author <a href="[email protected]">chenzy</a><br/>
 */
public class FileConstruct {

    public static void  main(String [] args) {
        // 文件路径名
        String pathname = "Z:\\file\\file.txt";
        File file1 = new File(pathname);
        System.out.println(file1);

        // 通过父路径和子路径字符串
        String parent = "Z:\\file";
        String child1 = "file.txt";
        File file2 = new File(parent, child1);
        System.out.println(file2);

        // 通过父级 File 对象和子路径字符串
        File parentDir = new File("Z:\\file");
        String child2 = "file.txt";
        File file3 = new File(parentDir, child2);
        System.out.println(file3);
    }

}
复制代码

Three ways to create a File object method shown above, the addition should be noted that: hard drive directory or file, directory or file does not affect the existence of the File object created in the hard disk in a File object represents.

2.2 Method of acquisition function

  • public String getAbsolutePath() : Returns the absolute path File instances

  • public String getPath() : File instances of the specified abstract pathname is converted to a path name string

  • public String getName() : Returns File instance directory or file name

  • public long length() : Returns File instance file length

In the hard disk Z: \ under file, create a file.txt file, the file contents are 26 English letters.

/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.file <br/>
 * Date:2020/1/4 11:01 <br/>
 *
 * @author <a href="[email protected]">chenzy</a><br/>
 */
public class FileGet {

    public static void main(String[] args) {

        File file1 = new File("Z:"+ File.separator + "file" + File.separator + "file.txt");
        System.out.println("文件绝对路径:"+file1.getAbsolutePath());
        System.out.println("文件构造路径:"+file1.getPath());
        System.out.println("文件名称:"+file1.getName());
        System.out.println("文件长度:"+file1.length()+"字节");

        System.out.println("----------------------");

        // 表示根目录,  在 windows 下:File.separator + "file" = "\\file"
        File file2 = new File(File.separator + "file");
        // 绝对路径
        System.out.println("目录绝对路径:"+file2.getAbsolutePath());
        // 构造 File 实例时的路径
        System.out.println("目录构造路径:"+file2.getPath());
        System.out.println("目录名称:"+file2.getName());
        // file 示例为目录,所以长度 = 0
        System.out.println("目录长度:"+file2.length());
    }

}
复制代码

File get methods exemplified above, it is worth noting that: the difference getPath () and getAbsolutePath () is that the former is acquired File path configuration example, which is acquired by the absolute path File instance. When constructing File instance path is an absolute path, the two are the same.

2.3 Absolute path relative path

  • Absolute Path: the complete path from the beginning of the letter
  • Relative path: relative to your current project directory path, this path often used in development
/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.file <br/>
 * Date:2020/1/4 11:29 <br/>
 *
 * @author <a href="[email protected]">chenzy</a><br/>
 */
public class FilePath {

    public static void main(String[] args) {
        // Z盘下的 file.txt 文件
        File file = new File("Z:\\file.txt");
        System.out.println(file.getAbsolutePath());

        // 项目下的 file.txt 文件
        File file2 = new File("file.txt");
        System.out.println(file2.getAbsolutePath());
    }

}

输出结果:
Z:\file.txt
Z:\IDEAProject\review\review_java\file.txt
复制代码

2.4 Method of determining function

Analyzing method has three main functions, the output is a Boolean value:

  • public boolean exists() : File instance representing the specified file or directory exists
  • public boolean isDirectory() : Specify File instance is not a directory
  • public boolean isFile() : File instance is not specified file
/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.file <br/>
 * Date:2020/1/4 11:37 <br/>
 *
 * @author <a href="[email protected]">chenzy</a><br/>
 */
public class FileIs {

    public static void main(String[] args) {
        File file1 = new File("Z:\\file\\file.txt");
        File file2 = new File("Z:\\file");
        // 判断是否存在
        System.out.println("Z:\\file\\file.txt 是否存在:"+file1.exists());
        System.out.println("Z:\\file 是否存在:"+file2.exists());
        // 判断文件
        System.out.println("Z:\\file\\file.txt 文件?:"+file1.isFile());
        System.out.println("Z:\\file 文件?:"+file2.isFile());
        // 判断目录
        System.out.println("Z:\\file\\file.txt 目录?:"+file1.isDirectory());
        System.out.println("Z:\\file 目录?:"+file2.isDirectory());
    }

}

输出结果:
Z:\file\file.txt 是否存在:true
Z:\file 是否存在:true
Z:\file\file.txt 文件?:true
Z:\file 文件?:false
Z:\file\file.txt 目录?:false
Z:\file 目录?:true
复制代码

2.5 to create and delete methods

  • public boolean createNewFile() : File instance is specified file does not exist, create an empty file
  • public boolean delete() : Delete the specified File instance represents a file or directory
  • public boolean mkdir() : Create a File instance represents the specified directory
  • public boolean mkdirs() : Create a File instance represents the specified directory and parent directory
/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.file <br/>
 * Date:2020/1/4 11:49 <br/>
 *
 * @author <a href="[email protected]">chenzy</a><br/>
 */
public class FileCreateDelete {

    public static void main(String[] args) throws IOException {
        System.out.println("-----创建文件------");
        // 文件的创建
        File file1 = new File("file1.txt");
        System.out.println("是否存在:"+file1.exists()); // false
        System.out.println("是否创建:"+file1.createNewFile()); // true
        System.out.println("是否存在:"+file1.exists()); // true

        System.out.println("-----创建目录------");

        // 目录的创建
        File file2 = new File("fileDir");
        System.out.println("是否存在:"+ file2.exists());// false
        System.out.println("是否创建:"+ file2.mkdir());	// true
        System.out.println("是否存在:"+ file2.exists());// true

        System.out.println("-----创建多级目录------");

        // 创建多级目录
        File file3= new File("fileDir1\\fileDir2");
        System.out.println(file3.mkdir());// false
        File file4 = new File("fileDir1\\fileDir2");
        System.out.println(file4.mkdirs());// true

        System.out.println("-----删除文件------");

        // 文件的删除
        System.out.println(file1.delete());// true

        System.out.println("-----删除目录------");
        
        // 目录的删除
        System.out.println(file2.delete());// true
        System.out.println(file4.delete());// false
    }

}
复制代码

Directory traversal 2.6

  • public String[] list() : Returns a String array representing all child files or directories specified File instance directory.

  • public File[] listFiles() : Returns an array of File, means that all the sub-file or directory specified File instance directory.

/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.file <br/>
 * Date:2020/1/4 12:02 <br/>
 *
 * @author <a href="[email protected]">chenzy</a><br/>
 */
public class FileList {

    public static void main(String[] args) {
        File dir = new File("Z:\\IDEAProject");

        //获取当前目录下的文件以及文件夹的名称,用处不大。
        String[] names = dir.list();
        for(String name : names) {
            System.out.println(name);
        }
        System.out.println("--------------------------------");
        //获取当前目录下的文件以及文件夹对象,拿到了文件对象,可以做更多操作,项目常用
        File[] files = dir.listFiles();
        for (File file : files) {
            System.out.println(file);
        }
    }

}
复制代码

It is worth noting: either list () or listFiles () method, the specified File instances must be physically present in the hard disk, otherwise it is impossible to traverse.

Third, recursive

3.1 What is recursion?

It refers to the program within a method call their own operations.

3.2 recursive classification

Recursively divided into two types:

  • Direct recursion: a method called themselves call their own.
  • Indirect recursion: A Method B Method can be invoked, B Method C Method calls, C A method of method calls.

Use recursive 3.3

  • Recursion limit must be qualified to ensure that recursion can be stopped, otherwise the memory stack overflow occurs
  • Although there are limited conditions, but not too much recursion recursion. Otherwise stack memory overflow will occur
  • Constructor disables recursion

Fourth, the use of recursion

If you do not know when to use recursion? That here there is a very simple law: When you clear recursion will not cause a memory leak that can be used; otherwise, do not use.

Recursive have a lot of usage scenarios, such as recursive summation, recursive factorial. The multi-level recursive directory traversal files, search for files that we used in development, so it is implemented:

/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.file <br/>
 * Date:2020/1/4 12:15 <br/>
 *
 * @author <a href="[email protected]">chenzy</a><br/>
 */
public class FileSearch {

    public static void main(String[] args) {
        // 创建 File 对象
        File dir  = new File("Z:\\IDEAProject");
        // 调用文件搜索方法
        searchFile(dir);
    }

    public static void  searchFile(File dir) {
        // 获取子文件和目录
        File[] files = dir.listFiles();
        // 循环遍历
        for (File file : files) {
            // 判断
            if (file.isFile()) {
                // 输出查找的目标文件的绝对路径
                if ("FileIs.java".equals(file.getName())){
                    System.out.println("目标文件路径:"+ file.getAbsolutePath());
                }
            } else {
                // 是目录,调用自身,形成递归
                searchFile(file);
            }
        }
    }

}

输出结果:
目标文件路径:Z:\IDEAProject\review\review_java\src\main\java\com\nasus\io\file\FileIs.java
复制代码

Fifth, the source address

Github Source Address: github.com/turoDog/rev...

At last

If you see here, like this article, then help "Forward" or the point of a "look", all right? 2020 I wish you riches. Micro-channel search " a good basket case ", welcome attention.

Reply to " 1024 " will give you a complete set of java, python, c ++, go , front-end, linux, algorithms, large data, artificial intelligence, applets, and English tutorials.

Reply " e-book " 50 + to send you this e-book java.

Complete Tutorial

Guess you like

Origin juejin.im/post/5e2129bce51d4558021a1290