Java IO stream -- use of File class

Use of File class

  • An object of the File class, representing a File or a File directory;
  • The File class is declared in Java Under IO package;
  • The methods involved in the File class are only methods for creating, deleting, renaming and obtaining relevant information of files or File directories, and do not involve the operation of writing or reading File contents. The operation of File content must be completed using IO stream;
  • The use of the File class often passes its instantiated object as a parameter to the stream constructor.

1. Instantiation of file class

  • Constructor 1: public File(String pathname), pathname: the path of the file

  • Constructor 2: public File(String parent, String child)

  • Constructor 3: public File(File parent, String child)

    @Test
    public void test1(){
        //Constructor 1: public File(String pathname)
        var file1 = new File("Hello.txt");//Relative to the files in the current package
        var file2 = new File("C:\\Users\\ASUS\\IdeaProjects\\Ther\\src\\JavaSE\\IO/Hello.txt");
    
        System.out.println(file1);
        System.out.println(file2);
    
        //Constructor 2: public File(String parent, String child)
        var file3 = new File("C:\\Users\\ASUS\\IdeaProjects","Ther");
        System.out.println(file3);
    
        //Constructor 3: public File(File parent, String child)
        var file4 = new File(file3,"src\\JavaSE\\IO/Hello.txt");
        System.out.println(file4);
    }
    
Relative path and absolute path

Relative path: the specified path relative to a certain path.

Absolute path: the path to the file or file directory including the drive letter

Separator

The path separator is related to the system. It is indicated by "\" by default in windows and Dos systems and "/" in UNIX and URL s (in fact, it will not report an error if it is used / in Windows). java programs support cross platform operation, so the path separator should be used with caution. In order to solve the hidden dangers of different separators in different systems, the File class provides a constant: public static final String separator, which dynamically provides separators according to the operating system.

2. Common methods of file class

Method nameexplain
public String getAbsolutePath()Get absolute path
public String getPath()Get relative path
public String getName()Get file name
File public File getParentFile()Gets the parent FIle path and returns the FIle type
public long length()Get file content length
public long lastModified()Get the last modification time of the file and return a timestamp
public boolean renameTo(File dest)rename
public String[] list()Returns all file names in the current file directory
public File[] listFiles()Returns all file paths under the current file directory
public boolean exists()Judge whether it exists
public boolean isDirectory()Determine whether it is a file directory
public boolean isFile()Determine whether it is a file
public boolean canRead()Is the file readable
public boolean canWrite()Is the file writable
public boolean isHidden()Whether the file is hidden
public boolean createNewFile()If the file does not exist, create a new file (the upper level file directory in the path exists)
public boolean delete()Delete a file or file directory (deleting a file directory requires that there be no files or file directories in the file directory)
public boolean mkdirs()Create multi-level file directory

Code example:

@Test
public void test2(){
    File file2 = new File("Hello.txt");
    File file1 = new File("C:\\Users\\ASUS\\IdeaProjects\\Ther\\src\\JavaSE\\IO\\Hello.txt");

    //Get absolute path public String getAbsolutePath()
    System.out.println(file1.getAbsolutePath());
    //Get relative path public String getPath()
    System.out.println(file1.getPath());
    //Get file name public String getName()
    System.out.println(file1.getName());
    //Get the parent file path and return File public File getParentFile()
    System.out.println(file1.getParentFile());
    //Get file content length public long length()
    System.out.println(file1.length());
    //The last modification time of the file returns a timestamp public long lastModified()
    System.out.println(new Date(file1.lastModified()));
    //public boolean renameTo(File dest): returns true after renaming the File successfully
    System.out.println(file1.renameTo(new File("C:\\Users\\ASUS\\IdeaProjects\\Ther\\src\\JavaSE\\IO\\Hello.txt")));

    System.out.println("----------------");
    System.out.println(file2.getAbsolutePath());
    System.out.println(file2.getPath());
    System.out.println(file2.getName());
    //File hello. In file2 Txt does not exist, so the parent path is null
    System.out.println(file2.getParentFile());
    System.out.println(file2.length());
    System.out.println(new Date(file2.lastModified()));
}

/*Output:
    C:\Users\ASUS\IdeaProjects\Ther\src\JavaSE\IO\Hello.txt
    C:\Users\ASUS\IdeaProjects\Ther\src\JavaSE\IO\Hello.txt
    Hello.txt
    C:\Users\ASUS\IdeaProjects\Ther\src\JavaSE\IO
    5
    Mon Jul 26 22:31:01 CST 2021
    true
    ----------------
    C:\Users\ASUS\IdeaProjects\Ther\Hello.txt
    Hello.txt
    Hello.txt
    null
    0
    Thu Jan 01 08:00:00 CST 1970
 */

@Test
public void test3(){
    File file = new File("C:\\Users\\ASUS\\IdeaProjects\\Ther");
    //public String[] list(): get all file names in the current directory
    String [] list = file.list();
    for (String i:
         list) {
        System.out.println(i);
    }

    //public File[] listFiles(): get all files in the current directory. The return type is File
    File [] files = file.listFiles();
    for (File f:
         files) {
        System.out.println(f);
    }
}

//Some common judgment methods
@Test
public void test4(){
    File file = new File("C:\\Users\\ASUS\\IdeaProjects\\Ther\\src\\JavaSE\\IO\\Hello.txt");

    //public boolean exists(): judge whether it exists
    System.out.println(file.exists());
    //public boolean isDirectory(): judge whether the File object is a File directory
    System.out.println(file.isDirectory());
    //public boolean isFile(): judge whether the File object is a File
    System.out.println(file.isFile());
    //public boolean canRead(): judge whether it is readable
    System.out.println(file.canRead());
    //public boolean canWrite(): judge whether it is writable
    System.out.println(file.canWrite());
    //public boolean isHidden(): judge whether to hide
    System.out.println(file.isHidden());


    /*Output:
        true
        false
        true
        true
        true
        false
         */
}

//Create, delete files or file directories
@Test
public void test5() throws IOException{
    File file1 = new File("Hi.txt");
    if(!file1.exists()){
        //public boolean createNewFile(): the method of creating a File and creating the File
        file1.createNewFile();
        System.out.println("File created successfully ");
    }else {
        //public boolean delete(): the method of deleting files
        file1.delete();
        System.out.println("File deleted successfully ");
    }

    //Parent directory exists
    File file2 = new File("C:\\Users\\ASUS\\IdeaProjects\\Ther\\Hello");
    if(!file2.exists()){
        //public boolean mkdir(): the method of creating a file directory
        //Return to judge whether the creation is successful. There are two cases of creation failure: 1 The file directory already exists, 2 The parent directory of the file does not exist
        Boolean flag = file2.mkdir();
        if (!flag){
            file2.mkdirs();
        }
        System.out.println("File directory created successfully ");

    }else {
        //Deleting a file directory requires that the file directory cannot have files
        file2.delete();
    }

    //Parent directory does not exist
    File file3 = new File("C:\\Users\\ASUS\\IdeaProjects\\Ther\\Hello\\Hi");
    if(!file3.exists()){
        Boolean flag = file3.mkdir();
        if (!flag){
            //public boolean mkdirs(): method for creating multi-level file directories
            file3.mkdirs();
        }
        System.out.println("File directory created successfully ");

    }else {
        file3.delete();
    }
}

Keywords: Java JavaSE

Added by Javizy on Fri, 14 Jan 2022 02:22:32 +0200