“This is the fourth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

The vast sea of thousands of thousands, thank you for this second you see here. Hope my article is helpful to you!

Wish you in the future, keep love, go to the mountains and seas!

I/O streams

Java operates on data through streams. IO streams are used to transfer data between devices, upload files and download files. The objects Java uses to operate on streams are in IO packages. Stream is a set of orderly data sequence with a starting point and an end point. Its essence is data transmission. According to the characteristics of data transmission, stream is abstracted into various classes to facilitate more intuitive data operation.

What it does: Establishes a transport channel between a data source and a destination.

The File type

Most IO stream operations are File operations, so Java provides a File class for manipulating files.

An overview of the

The java.io.File class is an abstract representation of File and directory pathnames. The File class is an object that encapsulates files and folders in a File system. It can be used to operate files and folders based on the idea of objects. It can be mainly used for creating, searching, and deleting files and directories.

Note: File represents File and directory information, not the contents of the File.

A constructor

public File(String pathname) {} // The absolute path of the file

public File(String parent, String child) {}// Specify the absolute path of the parent file and the absolute path of the child file

public File(File parent, String child) {}// Specify the relative paths of parent and child files

public File(URI uri) {} // The URI address of the file

// The following two constructors are private in the File class and cannot be called from outside
private File(String pathname, int prefixLength) {}

private File(String child, File parent) {}public File(String pathname) {}
Copy the code

As you can see, class File has six constructors: four public and two private.

The common construction methods are:

  • public File(String pathname): passes the givenPathname stringConvert to abstract pathname to create a new File instance.
  • public File(String parent, String child)From:Parent pathname string and child pathname stringCreate a new File instance.
  • public File(File parent, String child)From:Parent abstract pathname and child pathname stringsCreate a new File instance.

Take a look at the code demo:

Public File(String pathname)// File pathname
String pathName = "E:\\aaa.txt";
File file = new File(pathName);

//public File(String parent, String child
String parent = "E:\\aaa";
String child = "bbb.txt";
File file2 = new File(parent, child);

// public File(File parent, String Child) Through the parent File object and child path String
File parentDir = new File("E:\\aaa");
String child2 = "bbb.txt";
File file3 = new File(parentDir, child2);
Copy the code

“E:\aaa” “E:\aaa” “E:\aaa” “E:\aaa”

Since \ is an escape character in a string, if you only have one \, you will think that yours is an escape character, so you need two.

Tips:

  1. A File object represents a File or directory that actually exists on the hard disk.
  2. Whether files or directories exist in the path does not affect the creation of File objects.

Common methods for File

The following required files are based on this a.tb:

1. Obtain the function

  • public String getAbsolutePath(): Returns the absolute pathname string of this File.
  • public String getPath(): Converts this File to a pathname string.
  • public String getName(): returns the name of the File or directory represented by File.
  • public long length(): returns the length of the File represented by this File.
  • public long lastModified(): Gets the last modification time in milliseconds

Code demo below:

public class FileTest {
    public static void main(String[] args) {
        File file = new File("E:\\demo\\a.txt");

        // Public String getAbsolutePath() : Gets the absolute path
        System.out.println("getAbsolutePath:" + file.getAbsolutePath());/ / getAbsolutePath: E: \ demo \ a.t xt

        //public String getPath(): obtain the relative path
        System.out.println("getPath:" + file.getPath());/ / getPath: E: \ demo \ a.t xt

        //public String getName(): gets the name
        System.out.println("getName:" + file.getName());/ / getName: a.t xt

        //public long length(): obtain the length. The number of bytes
        System.out.println("length:" + file.length());/ / length: 20

        //public long lastModified(): get the lastModified time in milliseconds
        System.out.println("lastModified:" + file.lastModified());/ / lastModified: 1606645407343

        // Convert the format to the millisecond value.
        Date time = new Date(file.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = sdf.format(time);
        System.out.println(s);/ / the 2020-11-29 18:23:27}}Copy the code

Presumably this should not need to say much, see will use it, directly call on the line.

2. Judgment function

  • public boolean isDirectory() : Determines whether it is a directory
  • public boolean isFile() : Determines whether it is a file
  • public boolean exists(): Determines whether the system exists
  • public boolean canRead(): Determines whether it is readable
  • public boolean canWrite(): Determines whether writable
  • public boolean isHidden(): Determines whether to hide

As usual, continue with a wave of demonstrations, go:

public class FileTest2 {
    public static void main(String[] args) {
        File file = new File("E:\\demo\\a.txt");

        //public Boolean isDirectory(): indicates whether it is a directory
        System.out.println("isDirectory: " + file.isDirectory());//isDirectory: false

        //public Boolean isFile(): indicates whether the file is a file
        System.out.println("isFile: " + file.isFile());//isFile: true

        Public Boolean exists(): specifies whether exists
        System.out.println("exists: " + file.exists());//exists: true

        //public Boolean canRead(): determines whether it is readable
        System.out.println("canRead: " + file.canRead());//canRead: true

        //public Boolean canWrite(): indicates whether the file is writable
        System.out.println("canWrite: " + file.canWrite());//canWrite: true

        //public Boolean isHidden(): specifies whether to hide
        System.out.println("isHidden: " + file.isHidden());//isHidden: false}}Copy the code

Without further ado, look at the code! Read and understand!

3. Create a feature

  • public boolean createNewFile(): Create file If such a file exists, do not create it
  • public boolean mkdir() : Create folder If such a folder exists, do not create it
  • public boolean mkdirs(): Create a folder. If the parent folder does not exist, create it for you

Look at the file information before creation:

Then, as usual, continue with a wave of demonstrations and go:

public class FileTest3 {
    public static void main(String[] args) throws IOException {
        //public Boolean mkdir(): create a folder
        // Create a folder hello in the folder demo of disk E
        File file = new File("E:\\demo\\hello"); // The hello folder is not available
        System.out.println("mkdir: " + file.mkdir());
        System.out.println("Then check whether the folder exists:" + file.exists());

        //public Boolean createNewFile(): create file if such a file exists, it will not be created
        // Create a file hello. TXT in the folder hello under the demo directory on disk E
        File file2 = new File(file,"\\hello.txt");// The hello folder has already been created
        System.out.println("createNewFile: " + file2.createNewFile());
        System.out.println("To determine whether the file exists:" + file2.exists());

        //public Boolean mkdirs(): create a folder. If the parent folder does not exist, it will be created for you
        File file3 = new File("E:\\demo\\world\\world");// Can you create a two-level folder directly
        System.out.println("mkdirs: " + file3.mkdirs());
        System.out.println("Then check whether the folder exists:"+ file3.exists()); }}Copy the code

The first execution result can be seen:

mkdir: trueCheck whether the folder exists:true
createNewFile: trueCheck whether the file exists:true
mkdirs: trueCheck whether the folder exists:true
Copy the code

And now that the files or folders have been created, what happens if we run it again?

mkdir: falseCheck whether the folder exists:true
createNewFile: falseCheck whether the file exists:true
mkdirs: falseCheck whether the file exists:true
Copy the code

False for all method calls, which means that if there are files or folders there will be no more creation.

A quick question, which of the methods you create is likely to throw an exception? Look at the code, think that might be wrong

File file4 = new File("E:\\world\\world2"); 
System.out.println("mkdir: " + file4.mkdir());

File file5 = new File("E:\\world\\world2");
System.out.println("mkdirs: " + file5.mkdirs());

File file6 = new File("E:\\helloWorld\\helloWorld2"); 
System.out.println("createNewFile: " + file6.createNewFile());
Copy the code

The result of this operation can be seen:

mkdir: false
mkdirs: true
Exception in thread "main"Java.io.IOException: The system cannot find the specified path. at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:1012)
	at com.it.test1.FileTest3.main(FileTest3.java:33) 
Copy the code

Summary:

  1. mkdirIf the existing folder or parent directory does not exist, then false will be returned for not creating, otherwise create.
  2. mkdirsIf there is a folder, it will return false not create, otherwise create.
  3. createNewFileIf the file exists, it will return false not to create, otherwise create. If the parent directory does not exist, an error message is displayed indicating that the system cannot find the specified pathIOException.

4. Delete function

Now let’s look at the current folder information:

In the above process, we already have the hello folder and the hello. TXT folder in the directory and the world folder in the world folder.

  • public boolean delete(): Deletes the File or directory represented by “File”.

No more words, on the demonstration:

public class FileTest4 {
	public static void main(String[] args) {
        //public Boolean delete() : delete the File or directory represented by this File.
        // Let's delete the file we created before.
        //1. We delete the hello. TXT from the hello folder
        File file = new File("e:\\demo\\hello\\hello.txt");
        System.out.println("Delete hello.txt:" + file.delete());

        //2. What if I delete it again? What's going to be returned?
        System.out.println("Delete hello.txt:" + file.delete());

        //3. Next I want to delete the Hello folder.
        File file2 = new File("e:\\demo\\hello");
        System.out.println("Delete hello folder:" + file2.delete());

        //4. Next I want to directly delete the world folder in demo. We know there's a world folder in there. What's going to happen?
        File file3 = new File("e:\\demo\\world");
        System.out.println(Delete the World folder:+ file3.delete()); }}Copy the code

Let’s guess how successful was the deletion of the World folder?

Run the program result:

Delete the hello. TXT:trueDelete the hello. TXT:falseDelete hello folder:trueDelete the world folder:false
Copy the code

Note:

  1. As you can see, if we delete hello. TXT and then delete it, we return false which means the deletion failed.

  2. If there are still files or folders in the folder, the deletion will also fail. If we want to delete the world folder in demo directly, it will fail because there are folders in it.

  3. Like when we usually delete files, he will go to the recycle bin, then we use Java to delete, the file is also go to the recycle bin?

    You can see that our recycling bin is empty. Instead of going to the recycle bin, it was actually deleted by the JVM.

5. Other features

  1. Rename function

    • public boolean renameTo(File file)Rename:
    public class FileTest5 {
        public static void main(String[] args) {
            //public boolean renameTo(File file)
            File file = new File("e:\\demo\\a.txt");
            System.out.println("RenameTo." + file.renameTo(new File("e:\\demo\\b.txt")));/ / renameTo: true}}Copy the code

    Program running result:

    RenameTo:true
    Copy the code

    Let’s look at the file information again:

  2. Absolute path and relative path

    • Absolute path: The path from the drive letter, which is a complete path. Such as: e \ \ demo a.t xt.

    • Relative path: The path relative to the project directory, this is a convenient path that is often used in development. Such as: a.t xt.

      public class FileTest6 {
          public static void main(String[] args) {
              // bbb. Java file in drive E
              File f = new File("E:\\bbb.java");
              System.out.println(f.getAbsolutePath());
      
              // the bbb. Java file under the project
              File f2 = new File("bbb.java"); System.out.println(f2.getAbsolutePath()); }}Copy the code

      The running results are as follows:

      E:\bbb.java
      E:\IdeaWorkSpace\project_File\bbb.java
      Copy the code
  3. Directory traversal

    • public String[] list(): Returns an array of strings representing all the subfiles or directories in the File directory.
    • public File[] listFiles() : Returns an array of files, representing all the subfiles or directories in the File directory.

    Let’s continue the demo:

    public class FileTest7 {
        public static void main(String[] args) {
            File dir = new File("e:\\demo");
            //public String[] list(): returns an array of strings representing all subfiles or directories in the File directory.
            // Get the names of files and folders in the current directory.
            String[] names = dir.list();
            for(String name : names){
                System.out.println(name);
            }
    
            //public File[] listFiles(): returns an array of files representing all subfiles or directories in the File directory.
            // Get the files in the current directory and the folder objects. Once you get the file objects, you can get more information
            File[] files = dir.listFiles();
            for(File file : files) { System.out.println(file); }}}Copy the code

    Program running result:

    aaa
    b.txt
    bbb
    e:\demo\aaa
    e:\demo\b.txt
    e:\demo\bbb
    Copy the code

    Note: The File object that calls the listFiles method must represent an actual directory, otherwise null is returned and traversal cannot be performed.

6. Summary File

  1. File can be used to represent information about files and directories, but it does not represent the contents of files. The file can be read and written in subsequent IO streams.
  2. Whether files or directories exist in the path does not affect the creation of File objects. While creating the File object is fine, it is possible that subsequent operations referencing the File object may cause an error.
  3. The commonly used method is also at the end of one by one, here is no need to write again, hey hey!

conclusion

I believe you have a certain understanding of the File class IO stream, looking forward to waiting for prying IO stream teaching!

Of course, there are many streams waiting to watch together next time! Welcome to the next chapter!

So far, the world is closed for today, good night! Although this article is over, BUT I still, never finished. I will try to keep writing articles. The coming days are long, and the horse is slow!

Thank you for seeing this! May you be young and have no regrets!

Note: If there are any mistakes and suggestions, please leave a message! If this article is helpful to you, I hope you can give me a comment, thank you very much!