Table of contents
about storage
A computer is mainly composed of these parts ( von Neumann architecture )
-
CPU
-
memory
-
input device
-
output device
Memory refers to devices that can store data, including registers, buffers, memory, and hard disks. The speeds corresponding to CPU access range from fast to slow: registers >buffer>memory>hard disk .
- Register: It is the registration part of the central processing unit. It is a limited high-speed access memory directly integrated into the CPU. It is composed of some NOT gate combinations and is divided into general-purpose registers and special registers . It is characterized by small capacity, mainly stores instructions and data frequently accessed by the CPU, and the data is lost after power failure .
- Cache : The cache is actually a cache in the memory. It exists because when the CPU frequently accesses some data in the memory, it will take more time to read from the memory every time. Therefore, in There is a cache between the register and the memory, and some data frequently accessed by the CPU is stored in the cache, so that the efficiency will be improved. Its characteristic is that the size of the cache is also very small, it cannot store a large amount of data, and the data will be lost after power failure, and the data stored in the cache will be replaced by CPU access. (For example, if some data is frequently accessed by the CPU at the beginning, and then the data is stored in the cache, but it is no longer frequent, then the space for this data stored in the cache will be occupied by other frequently accessed data). The cache can be divided into a first-level cache and a second-level cache, and the speed of the first level is greater than that of the second level. Therefore, when the CPU accesses data, it first goes to the cache to see if there is any, and then reads it from the memory if it is not.
- Memory : Memory is divided into read-only memory (ROM) and random access memory (RAM). Among them, RAM is widely used. For example, the memory stick on our computer is RAM. Memory features: The storage space is much less than that of the hard disk, the access speed is faster, the data cannot be stored continuously, and the data will be lost after power failure .
- Hard disk : large storage space, very slow access speed, 3 or 4 orders of magnitude slower than memory. The data is stored for a long time, and the data will not be lost after power failure. ** Hard drives, U disks and other storage are classified as external storage, and their access speed is the slowest.
About the file
Let's first understand the file in the narrow sense (file). For I/O devices with persistent storage such as hard disks, when we want to save data, we often do not save it as a whole, but save it independently as a unit. This independent unit is abstracted into a file The concept is similar to the real documents on the desk.
In addition to the data content of the file, there is also some information, such as the file name, file type, file size, etc., which do not exist as the data of the file. We can regard this part of information as the meta information of the file.
At the same time, with more and more files, the system management of files has also been put on the agenda. How to organize files? A natural idea appeared, which is to organize according to the hierarchical structure—that is, our data The learned tree structure in the structure. In this way, a special file specially used to store management information was born, which is the concept of what we usually call a folder or directory.
The tree diagram looks like this
file path
How to locate our unique file in the file system has become the current problem to be solved. Here we introduce file paths, including absolute paths and relative paths.
absolute path
Each node in the tree can be described by a path starting from the root and reaching the node, and this description is called the absolute path of the file (absolute path). For example: file 1 in the figure
below The absolute path is D:/Photos/1/
relative path
In addition to describing the path from the root, we can describe the path from any node, and this description is called a relative path (relative path), a path relative to the current node.
For example, in the above figure, starting from the node of the photo to find file 1, the path is that
the path starting with . or ... is called a "relative path". First, specify a reference path (working directory), and the relative path starts from the reference path. , find the directory of the target.
file operation
In Java, a file (including a directory) is abstractly described through the java.io.File class. Note that having a File object does not mean that the file actually exists.
Construction method
Construct a file based on a path through the construction method.
The parameter is an absolute path or a relative path, and a FIle instance will be created according to the path. If the incoming string is empty, a null pointer exception will be thrown.
About common methods of File class
file read and write
This involves a concept flow
Stream, data transmission between devices is called stream
IO stream, which describes the direction of data flow, based on the memory, the input stream flowing into the memory, and the output stream flowing out of the memory
IO streams are further divided into byte streams and character streams. Character streams (Reader and Writer) are suitable for manipulating text files, and byte streams are suitable for manipulating binary files.
InputStream input stream
InputStream is just an abstract class, and a concrete implementation class is required to use it. There are many implementation classes of InputStream. It can basically be considered that different input devices can correspond to an InputStream class. We only care about reading from files now, so when using FileInputStream, there are two commonly used construction methods for FileInputStream. These two construction methods
are
actually They all have the same meaning, as shown in the figure below, the constructor whose parameter is String will first create a File object based on this String, and then pass the File object into another constructor, essentially creating a File object first, and then proceed to the rest of the steps.
Operations on file content:
- open a file
- close file
- read file
- Write files (3, 4 are key operations)
Regarding file reading and writing in Java, some classes are provided:
The first group: InputStream OutputStream byte stream: stream in bytes
The second group: Reader Writer character stream: stream in units of character stream
Streams are very common in computers, a vivid metaphor
When you need to pay attention to the common methods of InputStream
, if the file content reads data multiple times, after each reading task is completed, the cursor position will be recorded (that is, where it was read this time), and the next time the data is read, it will be Start reading from this position instead of re-reading each time
public class Demo6 {
public static void main(String[] args) throws IOException {
InputStream inputStream=null;
try (InputStream inputStream=new FileInputStream("./test2.txt")){
//1.打开文件
//2.读取文件
// while(true){
// int b=inputStream.read();//法一使用read()
// if(b==-1){
// //文件读完了
// break;
// }
// System.out.println(b);
// }
byte[] b=new byte[1024];
int len=inputStream.read(b);//法二使用read(byte[] b);
// System.out.println(len);
// for(int i=0;i<len;i++){
// System.out.println(b[i]);
// }
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above code, I used two methods to read the file
- Method 1: read byte by byte, integer b is the value corresponding to the byte
- Method 2: Store the read data in byte[]. Compared with the first method, the second method is more efficient. This byte[] acts as a buffer and reduces resource consumption on a lot of "distance" .
Running results
The third version with three parameters is the same as stuffing data into byte[] b, starting from b[off], and stuffing up to len bytes
Character reading with Scanner
In the above example, we saw that it is very cumbersome and difficult to directly use InputStream to read the character type, so we use a class that we are familiar with to complete the work, which is the Scanner class.
Construction method | illustrate |
---|---|
Scanner(InputStream is,String charset) | Use the charset character set to scan and read is |
Example 1
public class Demo8 {
// 对于文本文件, 还有更简单的写法~~
public static void main(String[] args) throws IOException {
InputStream inputStream=new FileInputStream("test2.txt");
Scanner scanner=new Scanner(inputStream);
String s=scanner.next();
System.out.println(s);
inputStream.close();
}
}
OutputStream output stream
write file:
Byte stream OutputStream/FileOutSream
Character stream Writer/FileWriter
shows that
OutputStream is also just an abstract class, and a specific implementation class is required to use it. We still only care about writing to the file now, so using FileOutputStream
The construction method of OutputStream is similar to that of InputStream. The essence of the two construction methods is the same. They also create a File object first, and then use this object as a parameter to enter another construction method.
Example 1 writes using a byte stream, using the write() method
public class Demo9 {
public static void main(String[] args) {
try (OutputStream outputStream = new FileOutputStream("test2.txt")) {
outputStream.write('h');
outputStream.write('e');
outputStream.write('l');
outputStream.write('l');
outputStream.write('o');
// 不要忘记 flush
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The first one is to write the parameter, and the parameter is int. When writing data, the data in the file will be cleared first, and then written. In addition, only the lower 8 bits of the shaping parameter will be written, and the upper 24 bits will be is ignored .
If you don't want to clear the old content when opening the file, you can pass in another parameter true, for example:
OutputStream outputStream = new FileOutputStream("test2.txt",true)
This will enable continuous writing, that is, when the file is opened, the content of test2.txt will not be cleared, but the content of test2.txt will continue to be written.
Example 2: use the write(byte[] b) method
public class Demo9 {
public static void main(String[] args) {
try (OutputStream outputStream = new FileOutputStream("test2.txt")) {
String s="hello java";
outputStream.write(s.getBytes());
// 不要忘记 flush
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The same is true for the output stream. If you write to the same file multiple times, the cursor position will be updated for each write, and the next write will continue to write from the cursor position. Of course, the cursor position can also be adjusted manually.
The effect of the third version of write with three parameters is similar to that of read, except that one writes and one reads.
Use PrintWriter to find our familiar methods
As opposed to Scanner, PrintWriter can also be used to simplify writing operations for character streams
As mentioned above, we have actually completed the output work, but it is always inconvenient. Next, we will process the OutputStream and use the PrintWriter class to complete the output, because
The PrintWriter class provides an example of the familiar print/println/printf method
public class Demo11 {
public static void main(String[] args) {
try (OutputStream outputStream = new FileOutputStream("test2.txt")) {
// 此处的 PrintWriter 的用法就和 System.out 是一样的了
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.println("aaa");
printWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}