(File operation) File file operation class

File file operation class

In the Java language, there is support for file operating system operations, and this support is defined in the java.io.File class, which means that in the entire java.io package, the File class is the only one that operates with the file itself ( Create, delete, rename) related classes, and if you want to perform File class operations, you must provide a complete path, and then you can call the corresponding method for processing.

The basic use of the File class:

Through the API documentation, it can be found that the File class is a subclass of the Comparable interface, so it can be sorted. When the File operation is performed, the access path needs to be set for it, so the path configuration is mainly handled by the construction method of the File class:

  • public File​(String pathname) Set the full path to be manipulated.
  • public File​(String parent, String child) Set parent path and child path.

Perform basic file operations:

  • Create a new file or directory: public boolean createNewFile() throws IOException
  • Determine whether the file or directory exists: public boolean exists()
  • Delete files or directories: public boolean delete()

Example: Use the File class to create a file (F:\Test\test.txt)

public static void main(String[] args) throws IOException {
        File file = new File("F:\\Test\\test.txt");
        if(file.exists()){  //文件存在
            file.delete();  //删除文件
        }else{  //文件不存在
            System.out.println(file.createNewFile());   //创建文件
        }
    }

It can be found through the code that the File class implements the processing of the file itself.

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112728400