Day 22 file and Io stream

File: an abstract representation of files and folders in java

Construction method:

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.

Functions of File:

Create function:

public boolean createNewFile() creates a file

public boolean mkdir() creates a folder

public boolean mkdirs() creates multi-level folders

be careful:
        1,Make sure you want to create files or folders
        2,The prince riding a white horse may not be the prince, but also the Tang monk, because the suffix is also part of the file name or a folder
 Delete function:
    public boolean delete()
    be careful:
        To delete a folder, the file must be empty
 Rename function
    public boolean renameTo(File dest)
Judgment function
    public boolean isDirectory()
    public boolean isFile()
    public boolean exists()
    public boolean canRead()
    public boolean canWrite()
    public boolean isHidden()
Basic acquisition function
    public String getAbsolutePath()
    public String getPath()
    public String getName()
    public long length()
    public long lastModified()
Advanced acquisition function
    public String[] list()
    public File[] listFiles()
Implementation idea and code of file name filter
    public String[] list(FilenameFilter filter)
    public File[] listFiles(FilenameFilter filter)

Recursion: the phenomenon of calling the method itself in the method definition.

be careful:

1. Figure out the difference between recursion and nesting: recursion occurs when a method is defined, and nesting occurs when a method is used

2. Recursion should have exit conditions (end conditions). If not, it becomes dead recursion

IO stream: (the input and output here take the java program as the reference)

Classification by flow direction:

Input stream

Output stream

Classification by data type:

Byte stream

Byte input stream read data InputStream

Byte output stream write out data OutputStream FileOutputStream

Character stream

Character input stream read data Reader

Character output stream write out data Writer

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.

If we want to realize IO operation, we 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 also the file representation file: the abstract representation of the path names of files and directories (folders).

Construction method:

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.

import java.io.File;

public class FileDemo1 {
    public static void main(String[] args) {
        //public File(String pathname) gets a File object according to a path
        //F:\a.txt is encapsulated into a File object
        File file = new File("F:\\a.txt");
        System.out.println(file);

        //public File(String parent,String child)
        //Parent path: F:\demo
        //Sub path: b.txt
        File file1 = new File("F: \\demo", "b.txt");
        System.out.println(file1);
        //public File(File parent,String child)
        //Parent path: F:\demo
        //Sub path: b.txt
        File file2 = new File("F: \\demo");
        File file3 = new File(file2, "b.txt");
        System.out.println(file3);
    }
}

Create function

public boolean createNewFile()

public boolean mkdir()

public boolean mkdirs()

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

public class FileDemo2 {
    public static void main(String[] args) {
        //Requirement: I want to create a folder demo2 under disk E
        //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
        //In the future, you can use some methods in the File class to create or delete
        File file = new File("E:\\demo1");
        //public boolean mkdir() creates a directory named by this abstract pathname. If the target folder already exists, it will not be created and returns false
        System.out.println(file.mkdir());
        //public boolean createNewFile() atomically creates a new empty file named by the abstract pathname if and only if the file with that name does not yet exist.
        try {
            System.out.println(file.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Requirement 2: I want to create a file b.txt in the demo2 folder under disk F
        //Encapsulate the target File into a File object
        File file1 = new File("E://demo1", "a.txt");
        try {
            System.out.println(file1.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //public boolean mkdirs() creates multi-level folders
        File file2 = new File("E:\\demo1\\demo2\\demo3\\demo4");
        System.out.println(file2.mkdirs());
        //Note 1: to create files in a directory, the premise is that the directory must exist!!
        File file3 = new File("E:\\demo3\\c.txt");
        try {
            System.out.println(file3.createNewFile());//The system cannot find the specified path
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Delete function:

public boolean delete()

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

public class FileDemo3 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\demo1\\a.txt");
        System.out.println(file.delete());
        File file1 = new File("a.txt");
        System.out.println(file1.createNewFile());
        File file2 = new File("aaa\\bbb\\ccc");
        System.out.println(file2.mkdirs());
        //Requirement: I want to delete aaa folder
        //Note: the directory to be deleted must be empty
        File aaa = new File("aaa");
        System.out.println(aaa.delete());

    }
}

Rename function

public boolean renameTo(File dest)

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

public class FileDemo4 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\demo1\\a.txt");
        System.out.println(file.createNewFile());
        File file1 = new File("E:\\demo1\\a.txt");
        File file2 = new File("E:\\demo1\\b.txt");
        System.out.println(file1.renameTo(file2));
    }
}

Judgment function

public boolean isDirectory()

public boolean isFile()

public boolean exists()

public boolean canRead()

public boolean canWrite()

public boolean isHidden()

import java.io.File;

public class FileDemo5 {
    public static void main(String[] args) {
        File file = new File("a.txt");

        //public boolean isDirectory() determines whether it is a folder
        System.out.println(file.isDirectory());
        //public boolean isFile() determines whether it is a file
        System.out.println(file.isFile());
        //public boolean exists() determines whether the target file or folder exists
        System.out.println(file.exists());
        //public boolean canRead() determines whether it is readable
        System.out.println(file.canRead());

        //public boolean canWrite() determines whether it is writable
        System.out.println(file.canWrite());
        //public boolean isHidden() judge whether to hide
        System.out.println(file.isHidden());
    }
}

Basic acquisition function

public String getAbsolutePath()

public String getPath()

public String getName()

public long length()

public long lastModified()

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileDemo6 {
    public static void main(String[] args) {
        File file = new File("a.txt");
        //public String getAbsolutePath()
        //Get absolute path, or full path
        System.out.println(file.getAbsoluteFile());
        //public String getPath()
        //Get relative path
        System.out.println(file.getPath());
        //public String getName()
        //Get name
        System.out.println(file.getName());
        //public long length()
        //The length obtained is the number of bytes
        System.out.println(file.length());
        //public long lastModified()
        //1645064059299 accurate to milliseconds
        //A timestamp is returned, which is the time from the completion and operation of the software to the creation of the file just now
        System.out.println(file.lastModified());
        //java converts timestamp and date
        //Date(long date)
        //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());
        System.out.println(date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        System.out.println(format);


    }
}

Advanced access function public String[] list() public File[] listFiles()

import java.io.File;

public class FileDemo7 {
    public static void main(String[] args) {
        File file = new File("E:\\demo1");
        //public String[] list()
        //Gets an array of the names of all files and folders in the specified directory
        String[] list = file.list();
        for (String s:list){
            System.out.println(s);
        }
        System.out.println("============================");
        //public File[] listFiles()
        //Gets the File object array formed by all files and folders in the specified directory
        File[] files = file.listFiles();
        for (File f:files){
            System.out.println(f);
        }
    }
}
result:
b.txt
demo2
============================
E:\demo1\b.txt
E:\demo1\demo2

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

1. Encapsulate the root directory of disk D into a File object

2. Get the File object array composed of all files or folders in the directory

3. Traverse each File object, and then determine whether it is an array of files

Yes: continue to judge whether to jpg suffix

Yes: output name

No: no matter him

No: no matter him

import java.io.File;

public class FileDemo8 {
    public static void main(String[] args) {
        File file = new File("D:\\");
        File[] files = file.listFiles();
        for (File s:files){
            if (s.isFile()){
                if (s.getName().endsWith(".jpg")){
                    System.out.println(s.getName());
                }
            }
        }
    }
}

Judge whether there is under disk D jpg file, if any, output the file name

1. First get all the files and folders, and then judge whether they are files and folders when traversing jpg suffix, and finally filter out the files that meet the conditions to obtain the name.

2. When acquiring, the acquired data meets the conditions, and we can output it directly.

Implementation idea and code of file name filter

public String[] list(FilenameFilter filter)

public File[] listFiles(FilenameFilter filter)

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

public class FileDemo9 {
    public static void main(String[] args) {
//create object
        File file = new File("D:\\");
        //public String[] list(FilenameFilter filter)
       String[] list= file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
//                return false;
                //Through the test, it is found that whether the files or folders in the directory should be obtained depends on the return value here
                //true, get and add to the array. If false, don't get and add to the array
                File file1 = new File(dir, name);
                boolean file2 = file1.isFile();
                boolean b = name.endsWith(".jpg");
                return file2&&b;
            }
        });
        for (String s: list){
            System.out.println(s);
        }
    }
}result:
a.jpg.jpg
import java.io.File;
import java.io.FilenameFilter;

public class FileDemo9 {
    public static void main(String[] args) {
//create object
        File file = new File("D:\\");
        //public String[] list(FilenameFilter filter)
       String[] list= file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
//                return false;
                //Through the test, it is found that whether the files or folders in the directory should be obtained depends on the return value here
                //true, get and add to the array. If false, don't get and add to the array
//                System.out.println(dir);
//          System.out.println(name);
                File file1 = new File(dir, name);
                boolean file2 = file1.isFile();
                boolean b = name.endsWith(".jpg");
                return file2&&b;
            }
        });
        for (String s: list){
            System.out.println(s);
        }
    }
}
result:
a.jpg.jpg

Recursion: the phenomenon of calling the method itself in the method definition.

Math.max(Math.max(a,b),c) is just the nesting of methods, not the recursive use of methods

give an example:

1. Once upon a time, there was a mountain and a temple in the mountain. There was an old monk in the temple. The old monk was telling a story to the little monk. The content of the story was:

Once upon a time, there was a mountain and a temple in the mountain. There was an old monk in the temple. The old monk was telling a story to the little monk. The content of the story was:

Once upon a time, there was a mountain and a temple in the mountain. There was an old monk in the temple. The old monk was telling a story to the little monk. The content of the story was:

...

The temple fell and the old monk died.

2. Learning big data -- high paying Employment -- earning money -- marrying a daughter-in-law -- giving birth to a baby -- earning tuition fees:

Learning big data -- high paying Employment -- earning money -- marrying a daughter-in-law -- giving birth to a baby -- earning tuition fees:

Learning big data -- high paying Employment -- earning money -- marrying a daughter-in-law -- giving birth to a baby -- earning tuition fees:

...

If you can't marry a daughter-in-law, you can't have a baby.

Precautions for recursion:

1. Recursion must have an exit (end condition), otherwise it will become dead recursion

2. The number of recursion should not be too many, otherwise it will cause stack memory overflow

3. Constructors cannot be recursive

public class DiGuiDemo1 {
    //Dead recursion
    public void show(){
        show();
    }
}

Requirements: find the factorial 5 of 5 with code= 5*4*3*2*1 = 5*4! = 5*4*3! = 5*4*3*2! = 5*4*3*2*1!

1. Solve with circulation

2. Solve with recursion

public class DiGuiDemo2 {
    public static void main(String[] args) {
//        int i=1;
//        for (int x=2;x<=5;x++){
//            i=i*x;
//        }
//        System. out. Println ("the factorial of 5 is:" + i);
//    }
        /**
         * Premise of recursive method:
         *  Return value type: int
         *  Parameter list: int i
         *
         *  Export conditions:
         *    if(i==1){return 1}
         *
         *  Recursive body logic:
         *     if(i!=1){
         *         return i*diGui(i-1);
         *     }
         */
        System.out.println(diGui(5));
    }

    public static int diGui(int i) {
        if (i == 1) {
            return 1;
        } else {
            return i * diGui(i - 1);
        }
    }
}

The case of immortal rabbit.

Suppose there is a pair of rabbits. From the third month of life, a pair of rabbits are born every month. After the third month, a pair of rabbits are born every month.

Suppose all rabbits don't die. Question: after 20 months, what are the logarithms of rabbits?

Law finding:

Logarithm of month

First month 1

Second month 1

The third month 2

The fourth month 3

Fifth month 5

The sixth month 8

...

From this courseware, the data of rabbit logarithm is:

1,1,2,3,5,8,13,21,34...

law:

1. Starting from the third item, each item is the sum of the first two items

2. Explain that the data of the first two items are known

How to achieve it?

1. Array implementation

2. Basic variable implementation

3. Recursive implementation

Define two variables as adjacent data

The first adjacent data: a=1,b=1

The second adjacent data: a=1,b=2

The third adjacent data: a=2,b=3

The fourth adjacent data: a=3,b=5

Law: for the next adjacent data, the value of a is the value of b last time, and the value of b is the sum of the previous adjacent data a+b

public class DiGuiDemo3 {
    public static void main(String[] args) {
        //Implementation with array
        int[] arr = new int[20];
        arr[0]=1;
        arr[1]=1;
        for (int i=2;i< arr.length;i++){
            arr[i]=arr[i-2]+arr[i-1];
        }
        System.out.println("The number of rabbits after the 20th month is:" + arr[19]);
        System.out.println("=============================");
        //Basic variable implementation
        //For the next adjacent data, the value of a is the value of the previous b, and the value of b is the sum of the previous adjacent data a+b
        int a=1;
        int b=1;
    for (int i=1;i<=18;i++){
        int temp=a;
        a=b;
        b=temp+b;
    }
        System.out.println(Fibonacc(20));

    }
    /**
     * Return value type: int
     * Parameter list: int i 20
     * <p>
     * Export conditions: 1 in the first month and 1 in the second month
     * Recursive condition: starting from the third month, the value of each month is the sum of the first two months
     */
    public static int Fibonacc(int i){
        //The first month is 1, and the second month is also 1
        if (i==1||i==2){
            return 1;
        }else {
            //Starting from the third month, the value of each month is the sum of the first two months
            return Fibonacc(i-1)+Fibonacc(i-2);
        }
    }
}
result:
The number of rabbits after the 20th month was 6765
=============================
6765

Traverse all the specified suffix file names in the specified directory E: \ number plus technology \ fifteen issues

analysis:

1. Encapsulate directories into File objects

2. Gets an array of all File objects in the directory

3. Traverse the array to get each File object

4. Judge whether the obtained File object is a File or a folder

1. If he is a folder, go back to step 2

2. If it is a file, judge whether the file name is in java suffix

If yes, output

No, skip

import java.io.File;

public class DiGuiDemo4 {
    public static void main(String[] args) {
        File file = new File("E:\\JAVA xm");
        getJavaFile(file);
    }

    public static void getJavaFile(File file) {
        //Gets an array of all File objects in the directory
        File[] files = file.listFiles();

        //Traverse the array to get each File object
        for (File f : files) {
            if (f.isDirectory()) {
                getJavaFile(f);
            } else {
                //Judge whether the file name is in java suffix
                if (f.getName().endsWith(".java")) {
                    //If yes, output
                    System.out.println(f.getName());
                }
            }
        }
    }
}

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

import java.io.File;

public class DiGuiDemo5 {
    public static void main(String[] args) {
        File file = new File("E:\\demo1");
        deteleFile(file);
    }
    public static void deteleFile(File file){
        //Get the File object array composed of all files and folders in the directory
        File[] files = file.listFiles();
if (file!=null){
    //Traverse the array to get each File object
    for (File f:files){
        //Determine whether the File object is a folder
        if (f.isDirectory()){
            deteleFile(f);
        }else {
            System.out.println(f.getName() + "---" + f.delete());
        }
    }
    System.out.println(file.getName() + "---" + file.delete());
}
    }
}
result:
b.txt---true
demo4---true
demo3---true
demo2---true
demo1---true

Classification of IO streams:

flow to:

Input stream read data

Output stream write data

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

Requirement: write a sentence to a.txt file: "big data, yyds"

analysis:

1. Because it is used to operate text files, it is best to use character stream. However, today we focus on byte stream. Character stream is born on the basis of byte stream

Now use byte stream

2. We need to write a sentence into the file. We need to use the output stream. Here, we use the byte output stream

Through the above analysis, the OutputStream is finally locked

After observing the API, it is found that OutputStream is an abstract class and cannot be instantiated directly

So we need to find a concrete implementation subclass to instantiate

FileOutputStream:

Construction method:

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.

Operation steps of byte output stream:

1. Create byte output stream object

2. Call method and write data

3. Release resources

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FileOutputStreamDemo1 {
    public static void main(String[] args) throws IOException {
        //Create byte stream output object
        //FileOutputStream(File file) creates a File output stream to write to the File represented by the specified File object.
//        File file = new File("b.txt");
//        //If the target file does not exist, it is created automatically
//        FileOutputStream fileOutputStream = new FileOutputStream(file);
        FileOutputStream fileOutputStream = new FileOutputStream("c.txt");
        System.out.println(fileOutputStream);
        fileOutputStream.write("sjd,hfhf".getBytes());
        fileOutputStream.close();
        fileOutputStream.write("djks".getBytes());//An error will be reported and writing cannot continue
    }
}

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)

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutoutStreamDemo2 {
    public static void main(String[] args) throws IOException {
        //Create byte output stream object
        FileOutputStream fileOutputStream = new FileOutputStream("d.txt");
        //public void write(int b)
        //97, the binary stored in the bottom layer, and the ASCII character corresponding to 97 is a
        fileOutputStream.write(97);
        fileOutputStream.write(48);
        fileOutputStream.write(65);
        //public void write(byte[] b)
        byte[] bytes={45,89,98,74};
        fileOutputStream.write(bytes);
        //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.
        fileOutputStream.write(bytes,1,3);
    }
}
Results in the document:
a0A-YbJYbJ

1. How to realize line feed?

Want to know why there is no line feed? Because we only write the bytes of the data, not the newline character

How to achieve it? Add a newline character during the writing section. Note: the newline character is not necessarily the same in different systems

Mac: \r

Windows: \r\n

Linux: \n

2. How to add?

import java.io.FileOutputStream;

public class FileOutputStreamDemo3 {
    public static void main(String[] args) throws Exception {
//        FileOutputStream fileOutputStream = new FileOutputStream("e.txt");
//        fileOutputStream.write("djksj".getBytes());
//        fileOutputStream.write("\r\n".getBytes());
//        fileOutputStream.write("dld".getBytes());
        //FileOutputStream(String name, boolean append)
        //Create a file output stream and write to the file with the specified name.
        //true indicates that data can be written additionally
        FileOutputStream fileOutputStream1 = new FileOutputStream("e.txt",true);
        fileOutputStream1.write("\r\n it's snowing today\r\n".getBytes());
//        fos.write("\r\n".getBytes());
       fileOutputStream1.write("But no snow was seen".getBytes());
       fileOutputStream1.close();
    }
}
Results in the document:
djksj
dld
 it's snowing today
 But no snow was seen

Keywords: JavaEE

Added by xtopolis on Wed, 23 Feb 2022 14:23:43 +0200