Understand file operations and IO

Understanding files

The files we usually refer to are files stored on the hard disk . Our usual important data content is stored in the form of files. The Java code we usually write is actually a way to operate memory. By applying for memory, space to perform operations.
Next, we will learn to operate the hard disk through the operation of files and IO interfaces. It can more directly operate the data files we usually use. This is indispensable whether in our work or in our studies . Short.

folder

We commonly refer to directory files as folders. Files are just like data. Our computers also manage files by managing data. As you
Insert image description here
can see, computers manage file directories through a tree structure .

file path

The path we are talking about is composed of the directories through which the file is found. According to the tree structure, we know that finding a file starts from the root and goes all the way along the branches of the tree. The Windows system starts from this computer. , so we usually omit this computer

  • Absolute path: refers to a specific path , starting with a drive letter. For example: C:\Program Files\Java\text
  • Relative path: refers to finding files (starting with .) from a given directory . For example: .\text
    注:Windows上文件与路径一一对应

File classification

Files are usually divided 文本文件into二进制文件

  • Text file: characters are stored
  • Binary file: stores binary data.
    We can open it through Notepad 1. If garbled characters appear, it is a binary file.

File operations

It mainly refers to some functions that can be completed through the file resource manager. It is provided in Java File类. A series of operations are completed through this class. Let's get to the point.

File class

File class exists java.ioin the package

Construction method

File(String pathname)            //根据文件路径创建一个新的File 实例

注:此处的文件可以不存在,只要目录可以找到,调用createNewFile()就可以创建该文件

Common methods

Modifiers and return value types method signature illustrate
String getParent() Return to File
String getName() Returns the plain file name of the FIle object
String getPath() Returns the file path of the File object
String getAbsolutePath() Returns the absolute path of the File object
String getCanonicalPath() Returns the modified absolute path of the File object
boolean exists() Determine whether the file described by the File object actually exists
boolean isDirectory() Determine whether the file represented by the File object is a directory
boolean isFile() Determine whether the file represented by the File object is an ordinary file
boolean createNewFile() Based on the File object, an empty file is automatically created. Returns true after successful creation
boolean delete() Based on the File object, delete the file. Returns true after successful deletion
void deleteOnExit() According to the File object, the annotated file will be deleted, and the deletion will not be performed until the end of the JVM run.
String[] list() Returns all file names in the directory represented by the File object
File[] listFiles() Returns all files in the directory represented by the File object, represented by a File object
boolean mkdir() Create the directory represented by the File object
boolean mkdirs() Creates the directory represented by the File object and, if necessary, creates intermediate directories
boolean renameTo(Filedest) Renaming files can also be regarded as our usual cut and paste operations.
boolean canRead() Determine whether the user has readable permissions on the file
boolean canWrite() Determine whether the user has writable permissions on the file

The above operations are relatively simple. Just note that the working directory in IDEA is the directory where the current project is located . \ represents the current working directory (base directory). .\ represents the parent directory of the current working directory.

Byte stream IO

Each stream object is divided into two types, input and output. Input refers to sending hard disk data to the CPU, and output refers to sending data from the CPU to the hard disk. In other words, the input and output we discuss are based on the CPU.

InputStream

Regarding the InputStream class, the method implemented in Java is an abstract class, so we cannot instantiate it directly. Instead, we usually use a class that implements this abstract class. At this stage, we do not involve the network and other content, but only care about the file. Read in, so use FileInputStream

Common methods

Modifiers and return value types method signature illustrate
int read() Read one byte of data and return -1 to indicate that it has been completely read.
int read(byte[] b) Read up to b.length bytes of data into b, and return the actual number read; -1 represents the completion of reading
int read(byte[] b,int off, int len) Read up to len - off bytes of data into b, start from off, and return the actual number read; -1 represents the completion of reading
void close() Close byte stream

Note : The closing operation is very necessary. Different from the previous habit of Java, the file is here 资源需要手动释放! ! !

FileInputStream

Construction method

sign illustrate
FileInputStream(File file) Use File to construct a file input stream
FileInputStream(String name) Construct a file input stream using a file path

FileInputStream instance

InputStream inputStream = new FileInputStream("D:/J-student-s:/JE-student-23-7-9");

An excellent writing habit (try with resources):

try(InputStream inputStream = new FileInputStream("D:/J-student-s:/JE-student-23-7-9")){
    
    
//这种写法可以自动释放资源
        }

There are three read versions provided in the previous InputStream. The return value -1 represents the end of reading. We write the following file reading operation:

import java.io.*;

public class Text1 {
    
    
    public static void main(String[] args) throws IOException {
    
    

        try(InputStream inputStream = new FileInputStream("D:\\student-Java-s\\JE-student-23-7-9\\text.txt");){
    
    
            while(true){
    
    
                int b = inputStream.read();
                if (b==-1){
    
    
                    break;
                }
                System.out.print(b);
                System.out.printf("%c\n",b);
            }
        }
    }
}

The running results are as follows:
Insert image description here

OutputStream

method

Modifiers and return value types method signature illustrate
void write(int b) Write the data to be given bytes
void write(byte[] b) Write all the data in the character array b into os
int write(byte[] b, int off, int len) Write the data starting from off in the character array b into os, write a total of len
void close() Close byte stream
void flush() We know that the I/O speed is very slow. Therefore, in order to reduce the number of device operations, most OutputStreams will temporarily write the data to a designated area of ​​​​the memory until the area is full or other Data is actually written to the device only when conditions are specified. This area is generally called the buffer. But one result is that part of the data we write is likely to be left in the buffer. The flush operation needs to be called at the end or at a suitable location to flush the data to the device.

Note: Similarly, we use FileOutputStreamto write files

FileOutputStream

Not much to say here, the specific construction method and usage are the same as FileInputStream

Character stream IO

Mainly use the abstract classes reader and writer , and the instance classes FileReader and FileWriter. Use read and writer to write and read, which is exactly the same as the byte stream. The only difference is that the character stream IO reads one character at a time, and the byte stream reads one word at a time. Festival, I won’t be too long-winded here~

Guess you like

Origin blog.csdn.net/m0_65038072/article/details/131615384