Day22 Java IO stream File, IO stream

File

summary:

If you want to realize IO stream operation, you must know the representation of files on the hard disk

Java provides a class that allows us to manipulate files on the hard disk: file. File is the representation of a file

File: abstract representation of file and directory (folder) pathnames.

Construction method of File class

public File(String pathname)

Create a new File instance by converting the given pathname string to an abstract pathname. If the given string is an empty string, the result is an empty abstract pathname.

public File(String parent,String child)

Create a new File instance from the parent pathname string and the child pathname string.

public File(File parent,String child)

Create a new File instance from the parent abstract pathname and child pathname strings.

Code example:

import java.io.File;

public class Demo1 {
    public static void main(String[] args) {
//        Get an object according to a path
        File file = new File("D:\\IdeaProjects\\a.txt");
        System.out.println(file);
//        Get the object according to the parent-child path
        File file1 = new File("D:\\IdeaProjects", "b.txt");
        System.out.println(file1);
//        Load the parent path into a File, and then get the object according to the parent-child path
        File file2 = new File("D:\\IdeaProjects");
        File file3 = new File(file2, "c.txt");
        System.out.println(file3);
    }
}

Results: the results obtained here are absolute paths

Member method of File class

Create function:

public boolean createNewFile()

Create a directory named by this abstract pathname. If the target folder already exists, it will not be created, and false will be returned

public boolean mkdir()

If and only if the file with that name does not exist yet, a new empty file named by the abstract pathname is created atomically.       

public boolean mkdirs() creates multi-level folders

Code example:

import java.io.File;
import java.io.IOException;

public class Demo2 {
    public static void main(String[] args) {
        File file = new File("D:\\IdeaProjects\\demo");
//        Encapsulated as a File object, it doesn't need whether the File or directory already exists. It just abstracts a path and represents it with File
//        Create a folder demo under the specified path
        System.out.println(file.mkdir());
//        Create a file a.txt under the demo, where you need to deal with exceptions during compilation
//        Encapsulate the target File into a File
        File file1 = new File("D:\\IdeaProjects\\demo\\a.txt");
        try {
            System.out.println(file1.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Create multi-level folder
        File file2 = new File("D:\\IdeaProjects\\demo2\\demo3\\demo4");
        System.out.println(file2.mkdirs());
//        Create a file in a directory that does not exist
        File file3 = new File("D:\\IdeaProjects\\demo5\\b.txt");
        try {
            System.out.println(file3.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

result:

 

The corresponding operation results will be generated in the corresponding hard disk folder:

   

Note: if you want to create files in a directory, the premise is that the directory must exist. And you need to know whether you need to create folders or files.

Delete function

public boolean delete() 

Code example:

import java.io.File;
import java.io.IOException;

public class Demo4 {
    public static void main(String[] args) {
//        Create a file
        File file = new File("D:\\IdeaProjects\\a.txt");
        try {
            System.out.println(file.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Delete file
        System.out.println(file.delete());
//        Delete multi-level folders. You must ensure that the contents of the deleted folder are empty
        File file1 = new File("D:\\IdeaProjects\\demo2\\demo3\\demo4");
        System.out.println(file1.delete());//Delete demo4
        File file2 = new File("D:\\IdeaProjects\\demo2\\demo3");
        System.out.println(file2.delete());//Delete demo3
        File file3 = new File("D:\\IdeaProjects\\demo2");
        System.out.println(file3.delete());//Delete demo2
    }
}

result:

Rename function

public boolean renameTo(File dest)

Code example:

import java.io.File;

public class Demo4 {
    public static void main(String[] args) {
        File file = new File("D:\\dlam.jpg");
        File file1 = new File("D:\\Dora A dream.jpg");
        System.out.println(file.renameTo(file1));
    }
}

Output result: true, and the name of the corresponding file is changed

Judgment function

public boolean isDirectory():

Determine whether it is a folder

public boolean isFile():

Determine whether it is a file

public boolean exists():

Determine whether the target file or folder exists

public boolean canRead():

Judge whether it is readable

public boolean canWrite();

Judge whether it is writable

public boolean isHidden():

Determine whether to hide

Code example: judge the a.txt file created in the demo folder before, and its attribute is readable, writable and not hidden

import java.io.File;

public class Demo5 {
    public static void main(String[] args) {
        File file = new File("D:\\IdeaProjects\\demo\\a.txt");
        System.out.println(file.isDirectory());
        System.out.println(file.isFile());
        System.out.println(file.exists());
        System.out.println(file.canRead());
        System.out.println(file.canWrite());
        System.out.println(file.isHidden());
    }
}

result:

Get function

Basic acquisition function

public String getAbsolutePath(): get absolute path

public String getPath(): get relative path

public String getName(): get the name

public long length(): gets the number of bytes of the file

public long lastModified(): get a timestamp of the file

Code example:

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo6 {
    public static void main(String[] args) {
        File file = new File("D:\\IdeaProjects\\demo\\a.txt");
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getPath());
        System.out.println(file.getName());
        System.out.println(file.length());
        System.out.println(file.lastModified());
//        The result of the direct output of this timestamp is incomprehensible and needs to be converted with the date class
//        Allocates a Date object and initializes it to represent the specified number of milliseconds after the standard reference time called "time", that is, January 1, 1970 00:00:00 GMT.
        Date date = new Date(file.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        System.out.println(format);

    }
}

result:

 

Advanced acquisition function

public String[] list(): gets an array of names of all files and folders in the specified directory

public File[] listFiles(): get the File object array formed by all files and folders in the specified directory

Code example:

import java.io.File;

public class Demo7 {
    public static void main(String[] args) {
        File file = new File("D:\\IdeaProjects");
        String[] list = file.list();
        for(String s : list){
            System.out.println(s);
        }
        System.out.println("-------------");
        File[] files = file.listFiles();
        for (File f : files){
            System.out.println(f);
        }
    }
}

result:

 

Demand: judge whether there is under disk D jpg suffix file, if any, output the file name

Analysis: package disk D into a File object, then obtain the File array composed of all files and folders in the directory, traverse the array to get each File object, judge whether each object is a File, and if so, judge whether it is a File jpg ends with output

Code implementation:

import java.io.File;

public class Demo8 {
    public static void main(String[] args) {
        File file = new File("D:\\");
        File[] files = file.listFiles();
        for(File f : files){
            if(f.isFile()){
                if(f.getName().endsWith(".jpg")){//Judge whether the file name is in End of jpg
                    System.out.println(f.getName());
                }
            }
        }
    }
}

Result: there is only one under disk D jpg file

Another implementation method:

Implementation idea and code of file name filter:

public String[] list(FilenameFilter filter)

public File[] listFiles(FilenameFilter filter)

These two codes only obtain the data that meets the conditions when obtaining the array composed of folders and files. There is no need to traverse. As long as the data is obtained, the direct output is the data that meets the conditions

In the source code, the filter is an interface with a Boolean accept method, so the accept method needs to be rewritten when calling

Code implementation:

import java.io.File;
import java.io.FilenameFilter;

public class Demo9 {
    public static void main(String[] args) {
        File file = new File("D:\\");
//        Create filter objects using anonymous inner classes
        String[] list = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
//                return false;
//                Depending on the file in the directory, the returned value does not depend on the folder
//                Pass the output test: dir is the absolute path where the file is located, and name is the file name
                File file1 = new File(dir, name);
                boolean b = file1.isFile();
                boolean b1 = name.endsWith(".jpg");
                return b && b1;
            }
        });
        for (String s : list){
            System.out.println(s);
        }
    }
}

Result: the same as the above output

recursion

Overview: the call method itself in the method definition.

Fibonacci sequence (rabbit problem) example: from the third day, the number of rabbits per day is the sum of the number of the first two days, and find the number of rabbits on the 20th day.

/*
    recursion
    Fibonacci sequence (rabbit problem)
 */
public class FDemo9 {
    public static void main(String[] args) {
        int rabbit = Fibonacci(20);
        System.out.println(rabbit);

    }
    public static int Fibonacci(int i){
        if(i==1 | i==2){
            return 1;
        }
        else{
            return Fibonacci(i-1)+Fibonacci(i-2);
        }
    }

}

result:

 

Recursively delete directories with content

Code implementation:

import java.io.File;

/*
        Recursively delete directories with content

        analysis:
            1,Get File object
            2,Get the File object array composed of all files and folders in the directory
            3,Traverse the array to get each File object
            4,Determine whether the File object is a folder
                Yes: return to step 2
                No: delete directly
 */
public class FDemo3 {
    public static void main(String[] args) {
        File file = new File("D:\\IdeaProjects\\Data15\\aaa");

        deleteFile(file);
    }
    public static void deleteFile(File file){
        File[] files = file.listFiles();
        for (File f : files){
            if(f.isDirectory()){
                deleteFile(f);
            }else{
                System.out.println(f.getName()+"---"+f.delete());
            }
        }
        System.out.println(file.getName()+"---"+file.delete());
    }
}

result:

IO stream

The IO stream is used to process data transmission between devices

Classification of IO streams:

flow to:

The input stream reads data from the hard disk to the Java program

The output stream writes out the data and outputs the data from the Java program to the hard disk

Data type:

Byte stream

Byte input stream read data InputStream

Byte output stream write out data OutputStream

Character stream

Character input stream read data Reader

Character output stream write out data Writer

Byte stream:

Write data:

OutputStream FileOutputStream creates a File output stream to write to the File represented by the specified File object.

Requirement: enter a line of "yyds" into a.txt under D:\IdeaProjects\demo.

It's best to use character stream to operate here, but byte stream to operate here

OutputStream is used here. It is an abstract class and cannot be instantiated directly.

So we need a subclass of FileOutputStream

Construction method of FileOutputStream:

FileOutputStream(File file) creates a File output stream to write to the File represented by the specified File object.

FileOutputStream(String name) creates a file output stream and writes it to the file with the specified name.

Code implementation:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class IOdemo1 {
    public static void main(String[] args) throws Exception{
        File file = new File("D:\\IdeaProjects\\demo\\a.txt");
        FileOutputStream fos = new FileOutputStream(file);
//      If there is no target file here, it will be created automatically
        fos.write("yyds".getBytes());
//        If you continue at this time, yyds will be overwritten
        //Release resources
        //close() closes the file output stream and frees any system resources associated with the stream.
        fos.close();
    }
}

The output result is nothing, but there is yyds in the a.txt file

It is mentioned in the code that resources need to be released after the operation of writing data, otherwise the stack memory will be occupied all the time. If there are many subsequent operations, memory overflow may be caused.

Several methods of writing data in byte output stream:

public void write(int b)

public void write(byte[] b)

public void write(byte[] b,int off,int len): writes len bytes from the specified byte array at offset off to the file output stream.

Code example:

import java.io.FileOutputStream;

public class IOdemo2 {
    public static void main(String[] args) throws Exception {
        //Create byte stream output object
        FileOutputStream fos = new FileOutputStream("D:\\IdeaProjects\\demo\\a.txt");

        //public void write(int b)
        //97, the binary stored in the bottom layer, and the ASCII character corresponding to 97 is a
        fos.write(97);
        fos.write(48);
        fos.write(65);

        //public void write(byte[] b)
        byte[] byts = {97, 98, 99, 100, 101};
        fos.write(byts);

        //public void write(byte[] b,int off,int len)
        //Writes len bytes from the specified byte array at offset off to the file output stream.
        fos.write(byts, 1, 3);

        //Release resources
        fos.close();
    }
}

Output result: you need to view it in a.txt:

When you use FileOutputStream to create a new object after releasing resources, and then add content to it, the previous content will be overwritten.

Append and wrap:

FileOutputStream(String name, boolean append) creates a file output stream and writes the file with the specified name. true indicates that data can be written additionally

Code example:

import java.io.FileOutputStream;

public class IOdemo3 {
    public static void main(String[] args) throws Exception{
        FileOutputStream fos = new FileOutputStream("D:\\IdeaProjects\\demo\\a.txt",true);
//            To realize line feed, you only need to add a line feed character
        fos.write("\r\n it's snowing today\r\n".getBytes());
        fos.write("But there is no snow".getBytes());
        fos.close();
    }
}

 

Output result:

Under what circumstances, use byte stream or character stream. If you operate Notepad to open data that you can understand, use character stream. If you can't understand, use byte stream
If you don't know what stream to use, use byte stream. Character stream appears based on byte stream.

Keywords: Java Back-end

Added by cartoonjunkie on Thu, 17 Feb 2022 18:55:48 +0200