Day11 files and input / output streams

day11 file and input / output stream

file

Why learn the File class?
Because in the operating system, the data that needs to be permanently saved exists in the form of files, if you want to operate these permanently saved data, you must first describe and represent the files in the java language

Pathname:

1. The absolute pathname is a complete pathname. You can locate the file it represents without any other information
windows: E:\demo\first\a.txt

2. Instead, relative pathnames must be interpreted using information from other pathnames (incomplete pathnames)
windows: (e:\demo))second\a.txt

Who is the default relative path in the java language?
By default, Java Classes in the IO package always resolve relative pathnames based on the current user directory. This directory is controlled by the system property user Dir specifies, usually the calling directory of the Java virtual machine.

String userDir = System.getProperty("user.dir");//Access method of absolute path of current directory

It is used to display the current directory. The subsequent relative path is relative to this path

If you want to modify the relative path, do the following:

Click this button

Finally, select the application

Path representation:
1. For UNIX like (MacOs) platforms, the absolute pathname is always prefixed with "/". Relative pathnames have no prefix. The prefix of the absolute pathname representing the root directory is "/" and the name sequence is empty.
Absolute path: / home / ZS / 6379 conf
Relative path: zs/a.txt
Root directory:/

2. For Microsoft Windows Platforms, the pathname prefix containing the drive letter consists of a drive letter and a ":". If the pathname is an absolute pathname, it may also be followed by "\“
Absolute path: e:\zs\a.txt
Relative path: no drive letter prefix zs\a.txt

File class constructor

File class overview: Note abstraction

Abstract representation of file and directory pathnames
1. One File Class object, which can be used to represent a file or a directory
2. One File Class object, which represents the file or directory represented by a pathname
3. Abstract? As opposed to physical existence, Because one File Object represents a file or directory identified by a pathname,
The file or directory determined by the pathname does not necessarily exist physically.

Construction method of File object:

// Create a File object to represent a File specified by the specified path name string (either absolute path or relative path) table
File (String pathname)


// Specify the pathname of the File represented by our File object in a way similar to relative path
//eg:
//File file1 = new File("f:\\Program Files (x86)\\Java_project", "a.txt");
//  parent:  f:\\Program Files (x86)\\Java_project
// child: a.txt
File (String parent, Sting child)



// Specify the pathname of the File represented by our File object in a way similar to relative path
// Parent parent path is represented by a File object
File (File parent, String child)

Create function

 // Physically creates the File represented by the current File object
  public boolean createNewFile()//true will be returned if the creation is successful. false will be returned if the creation has already existed or failed

  // Create directory
  // The target directory can only be created under an existing directory
  public boolean mkdir()
  public boolean mkdirs()

   mkdir and mkdirs Differences in creating directories:
   1. mkdir You can only create a new directory under an existing directory
   2. mkdirs When the target directory to be created, if the parent directory of the target directory does not exist, it will create the parent directory of the nonexistent target directory together with the target directory

Rename function

Rename function
       // Renames the File represented by the current File object to the name represented by the specified File object
       public boolean renameTo(File dest)

1. When the source file and the modified target file are in the same directory: the effect is only renaming
2. When the source file and the modified target file are not in the same directory:
    a. move file
    b. rename

Judgment function

Judgment function
public boolean isFile() // Judge whether the File object represents a File
public boolean isDirectory() //Determine whether the File object represents a directory
public boolean exists() //Judge whether the File or directory represented by the File object physically exists


The latter three are not commonly used:
public boolean canRead() // Judge whether the File represented by the File object is readable
public boolean canWrite() // Judge whether the File represented by the File object is writable
public boolean isHidden() // Judge whether the File is a hidden File, and judge whether the File represented by the File object is a hidden File

Either directories or files are stored in the host

Basic acquisition function

public String getAbsolutePath() //Gets the absolute path of the abstract File represented by the File object

String userDir = System.getProperty("user.dir");//Access method of the absolute path of the current directory (compare the two methods)

public String getPath() //Gets the abstract File represented by the File object, pathname string
public String getName() //Get the name of the file or directory

public long length()
Returns the length of the file represented by this abstract pathname. If this pathname represents a directory, the return value is uncertain.
The length of the file represented by this abstract pathname, in bytes (viewed in file properties); If the file does not exist, 0 is returned L

public long lastModified()
Returns the time when the file represented by this abstract pathname was last modified.
Indicates the time when the file was last modified long Value, with time point (January 1, 1970, 00:00:00 GMT)Expressed in milliseconds between

Output results corresponding to various methods:

File file = new File("test\\a.txt");

 //public String getAbsolutePath()
 String absolutePath = file.getAbsolutePath();
 System.out.println(absolutePath); //E:\wangdao\short-2022\File\a.txt

//public String getPath()
 String path = file.getPath();
 System.out.println(path); //test\a.txt

 //public String getName()
 String name = file.getName();
 System.out.println(name); //a.txt

 // public long length()
 long length = file.length();
 System.out.println(length);

Advanced access features:

public String[] list()//Returns a reference address
a. Returns an array of strings that specify the files and directories in the current directory.
b. If this abstract pathname does not represent a directory, this method returns null
c. Otherwise, an array of strings is returned, and each array element corresponds to each file or directory in the directory
d. Each string is a file name, not a full path


public File[] listFiles()
a. Return a File Arrays, these File Object represents a file or directory in this directory.
b. If this abstract pathname does not represent a directory, this method returns null
c. Otherwise, return a File Object array, each array element corresponds to each file or directory in the directory

Demo code for testing the first method: (not commonly used, because only the reference address of one string can be returned)

File file = new File("f:\\demo");
String[] list = file.list();
System.out.println(Arrays.toString(list));

Test result: [a.txt, empty, second]

Test the demonstration code of the second method: (commonly used, because this files [] is an array of File objects. If you want to print it completely, you can use the following methods, but if you point to one of the objects, you can print it directly with South (files [0])

File[] files = file.listFiles();
System.out.println(Arrays.toString(files));

Test results: [f:\demo\a.txt, f:\demo\empty, f:\demo\second]

be careful:

Obtained by the above method files[]Object array can be obtained directly by using the following methods
System.out.println(files[i]);//I is a constant in the range of the object array, because the bottom layer of the South method calls files ToString method, so that the absolute path of files[i] can be displayed
  1. Judge the empty directory by whether the length of the returned array is 0 String[] list()
  2. Whether it is a file or a directory depends on file Whether list() is a null pointer, or use isFile() and isDirectory() to determine whether it is a file or a directory

Custom get function

If we want to get a sub file or sub directory under a directory that meets special conditions
a. Get all text files in the target directory
b. Get all subdirectories under the target directory

Implementation method:

public static void main(String[] args) {
    File targetDir = new File("e:\\demo");
    // Find text files in the destination directory
    //findTXT(targetDir);

    // Find subdirectories in the destination directory
    //findDirectory(targetDir);
}
 public static void findTXT(File dir) {                              //a
        // Get all sub files or subdirectories in the current directory
        File[] files = dir.listFiles();

        for (int i = 0; i < files.length; i++) {
            File targetFile = files[i];
            // Filter according to specified criteria
            if (targetFile.isFile()) {
                // If a File object represents a File
                String name = targetFile.getName();
                if (name.endsWith(".txt")) {
                    System.out.println("find txt file: " + files[i]);
                }
            }
        }
    }

public static void findDirectory(File dir) {                        //b

    // Get all sub files or subdirectories in the current directory
    File[] files = dir.listFiles();

    for (int i = 0; i < files.length; i++) {
        File targetFile = files[i];
        // Filter according to specified criteria
        if (targetFile.isDirectory()) {
            // If a File object represents a directory
            System.out.println("find dir: " + targetFile);

        }
    }
}

However, the scalability of this method is not strong, and the code needs to be copied again to judge what file is, which is very bad. Therefore, an abstract class or interface (generally used interface) is required to write the redundant code only once

Filter (an interface)

// In the current directory, find multiple sub files or subdirectories that meet the specified conditions
File[] listFiles(FileFilter filter)


//How to describe a filter condition? FileFilter interface

public interface FileFilter {
   // Judge whether a File object meets the specified conditions
   // Return true if the condition is met
   // false is returned if the condition is not met
   boolean accept(File pathname);
}

For this topic: how to write a filter

class MyFileFilter implements FileFilter{
    @Override//The method rewriting here must be rewritten because there is an abstract method in the filter
    public boolean accept(File targetFile) {
        if(!targetFile.isFile()){
            return false;
        }
        String name = targetFile.getName();
        return name.endsWith(".txt");
    }
}

Rewrite the new method of finding text files:

public static void myListFiles(File targetDir,FileFilter fileFilter){
    File[] files = targetDir.listFiles();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        if(fileFilter.accept(file)){
            System.out.println(file);
        }
    }
}

Finally, call the method that you wrote in the main function:

public static void main(String[] args) {
        File file = new File("f:\\demo");
        MyFileFilter myFileFilter = new MyFileFilter();
        myListFiles(file,myFileFilter);

    }

In this way, the task of finding text documents is completed and redundant code is avoided

Finally, let's take a look at the methods defined by jdk:

The method in the main function reads as follows:

public static void main(String[] args) { 
    File file = new File("f:\\demo");
	MyFileFilter myFileFilter = new MyFileFilter();
    File[] files = file.listFiles(myFileFilter);//What is returned here is an array of objects, which is different from the methods we define ourselves

    for (int i = 0; i < files.length; i++) {
        System.out.println(files[i]);
    }
}

The method of jdk implementation here is abstract and difficult to understand, so let's take a look at its source code

public File[] listFiles(FileFilter filter) {
    //Get all the sub files in the current directory and the name of the sub directory
    String ss[] = normalizedList();
    //If the current File object is found to be a File, null is returned
    if (ss == null) return null;
    ArrayList<File> files = new ArrayList<>();
    //Here is a dynamic array (difficult) (it can be expanded automatically) < > the things in it are generic
    //Put data (file only) objects
    //Example: fileslist Add (file1) adds a file1 object
    //Store qualified File objects
    for (String s : ss) {
    //The enhanced for loop creates a File object for each current directory or File
        File f = new File(s, this);
        //This is a private construction method to create an object in the current directory
        if ((filter == null) || filter.accept(f))
            files.add(f);
    }
    File[] f = new File[files.size()];
    return files.toArray(f);//Return the elements of the object array to the File [] array in turn
}

Summary: the important point here is to create this object

Input and output streams

Introduction of input / output stream

Create an output stream object

demand: adopt OutputStream Object to finish exporting to a text file hello world"
   a. But notice, OutputStream Is an abstract class, if you want to use OutputStream Object, only its subclass objects can be used to complete the write function.
   b. It should also be noted here that although the written data is text data, the character stream has not been learned, so the byte stream is used first.

Create a flow object(OutputStream Subclass object)
    FileOutputStream Construction method of
    // Create a File byte output stream object and write data to the File specified by the File object
    1.FileOutputStream(File file)
    // Create a file byte output stream object to write data to the file specified by the pathname string name
    2.FileOutputStream(String name)

    be careful:
     The pathname string here or File Object that represents only the target file, not the directory

Call the write method

public void write(int b)
    a. Writes the specified byte to this output stream
    b. write The general convention is to write a byte to the output stream.
    The bytes to be written are parameters b Eight low positions. b The 24 high bits of will be ignored.

    public void write(byte[] b)
    take b.length Bytes from the specified byte Array writes to this output stream

    public void write(byte[] b, int off,int len)
    Will specify byte Offset from array off Beginning len Bytes are written to this output stream

Some problems of byte stream writing data

1 What exactly does creating a byte output stream do?
    1). establish FileOutputStream When it comes to objects, jvm First, go to the operating system and find the target file
          a. When it is found that the target file does not exist, jvm The target file is created first(Content is empty)
          b. When the target file is found to exist, jvm By default, the contents of the target file will be emptied first. It is best to prepare
             Give Way, FileOutputStream, Start writing data from the file header
   2). In memory, create FileOutputStream object
   3). stay FileOutputStream Establish a data transmission channel between the object and the target file

2 After the data is written successfully, why close()?
    a. Close this output stream
    b. Release all system resources related to this flow.

3 How to wrap data? 
String s = System.lineSeparator();//In this case, s represents the newline character in the current system
 judge windows Is the newline character under\r\n,Just use one method:
System.out.println("\r\n".equals(s));//See that the output result is true to verify the conclusion


Line breaks are expressed differently in different operating systems:
    class unix In the operating system:'\n'
    windows Default newline representation: '\r'+'\n' use windows Built in text editor for\n Whether there is line feed effect is also related to the operating system version



4 How to write additional data?
You can create FileOutputStream Object, indicating the method of writing data to the file(Write from the end of the file)
There are two construction methods:
    public FileOutputStream(File file,boolean append)//eg:
    public FileOutputStream(file,true)
    1. Create a specified File Object to write data to the file output stream.
    2.If the second parameter is true,Writes bytes to the end of the file, not to the beginning of the file.


    public FileOutputStream(String name,boolean append)
    1. Create a file with the specified name The output file stream in which data is written.
    2. If the second parameter is true,Writes bytes to the end of the file, not to the beginning of the file

    a. For the same output stream object, the data written multiple times will be written to the target file in turn,
    The data written first is first, and the data written later is last(Non append write)

    b. The so-called append write refers to writing data to a file for different output stream objects. The so-called append write refers to
    When using different output stream objects to write data to a file, it starts writing after the file has content

  
5 to I/0 Stream operation plus exception handling?

For question 5: (wrap with try catch code block)

public static void main(String[] args) {

    FileOutputStream fos = null;

    try {
        //Create FileOutputStream
        String st = "hello,world!";

        fos = new FileOutputStream("a.txt");
        fos.write(st.getBytes());

        String lineSeparator = System.lineSeparator();
        fos.write(lineSeparator.getBytes());

        fos.write(st.getBytes());

        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Keywords: Java

Added by wolf on Mon, 17 Jan 2022 12:51:58 +0200