The buffer and buffer processing method is the basis for all I/O operations. The term "input and output" only makes sense for data migration and removal from the cache. Remember it at any time. Generally, the process executes OS I/O requests, including data from the buffer (write operation) and data fill buffer (read operation ). This is the overall concept of I/O. The mechanism for executing these transfer operations within the operating system can be very complicated, but it is very simple in concept. We will discuss it in a small part.
The preceding figure shows a simplified "logic" diagram that shows how block data is migrated from an external source, such as a disk, to a process storage area (such as RAM. First, the process requires the buffer to be filled by the read () system call. This system call causes the kernel to issue a command to the disk control hardware to obtain data from the disk. The disk controller directly writes data to the memory buffer of the kernel through DMA, without the help of the primary CPU. When the read () operation is requested, once the disk controller completes the cache filling, the kernel copies data from the temporary cache of the kernel space to the cache specified by the process.
Note that when the kernel tries to cache and prefetch data, the data requested by the process in the kernel space may be ready. In this case, the data requested by the process will be copied. If the data is unavailable, the process is suspended. The kernel reads data into the memory.
Virtual memory
You may have heard of virtual memory many times. Let me introduce it again.
All modern operating systems use virtual memory. Virtual memory means that the manual or virtual address replaces the physical (hardware RAM) memory address. Virtual addresses have two important advantages:
Multiple virtual addresses can be mapped to the same physical address.
A virtual address space can be larger than the actual available hardware memory.
In the above introduction, copying from the kernel space to the end user cache seems to have added additional work. Why not tell the disk controller to directly send data to the user space cache? Well, this is implemented by virtual memory. Use advantage 1 above.
By ing the kernel space address to the same physical address as the virtual address of a user space, the DMA hardware (only accessible to the physical memory address) can fill in the cache. This cache is visible to both kernel and user space processes.
This eliminates the copy between the kernel and the user space, but requires the same page alignment between the kernel and the user buffer. The buffer must use a multiple of the block size of the disk controller (usually a 512-byte disk sector ). The operating system divides its memory address space into pages, which are fixed-size byte groups. These memory pages are always multiples of the disk block size and usually 2 times (simplified addressing ). Typical memory page sizes are 1024, 2048, and 4096 bytes. The page size of the virtual and physical memory is always the same.
Memory paging
To support the 2nd advantages of virtual memory (having a addressable space larger than physical memory), virtual memory paging (usually called Page switching) is required ). This mechanism allows pages in the virtual memory space to be permanently stored on the external disk for storage, thus providing space for other virtual pages to be placed in the physical memory. In essence, the physical memory serves as the cache for the paging area. The paging area is the space on the disk. When the content of the memory page is forced to switch out of the physical memory, it is saved here.
Adjust the memory page size to a multiple of the disk block size, so that the kernel can directly send commands to the disk controller hardware, write the memory page to the disk or reload it as needed. It turns out that all disk I/O operations are completed at the page level. This is the only way for data to move between disk and physical memory on a modern paging operating system.
A modern CPU contains a subsystem named memory management unit (MMU. The device is logically located between the CPU and physical memory. It contains the ing information converted from the virtual address to the physical memory address. When the CPU references a memory location, MMU determines which pages need to reside (usually by shifting or shielding some of the addresses) and converts virtual page numbers to physical page numbers (implemented by hardware, fast ).
FILE-oriented, Block I/O-oriented
File I/O always occurs in context switching of the file system. The file system is totally different from the disk. The disk stores data in segments, each of which is 512 bytes. It is a hardware device and has no idea about the semantics of the stored files. They only provide a certain number of data storage slots. In this regard, the segment of a disk is similar to the memory paging. They all have a uniform size and are a large addressable array.
On the other hand, the file system is a high-level abstraction. A file system is a special method for arranging and translating data stored on a disk (or other block-oriented devices that can be accessed randomly. The code you write almost always interacts with the file system, instead of directly interacting with the disk. The file system defines the file name, path, file, and file attributes.
A file system organizes (in a hard disk) a series of even data blocks. Some blocks store metadata, such as the ING, directory, and Index of idle blocks. Other blocks contain actual file data. The metadata of a single file describes which parts contain the file data, the end position of the data, and the last update time. When a user process sends a request to read file data, the file system can accurately locate the data location on the disk. Then take actions to put these disk sectors into the memory.
A file system also has a page concept. Its size may be the same as that of a basic memory page or its multiples. The typical file system page size ranges from 2048 to 8192 bytes, and is always a multiple of the basic memory page size.
The paging file system can perform the following logical steps to execute I/O:
Determine which file system pages the request spans (a set of disk segments ). The file content and metadata on the disk may be distributed across multiple file system pages, which may be discontinuous.
Allocate enough kernel space memory pages to save the same file system page.
Establishes the ing between these memory pages and the file system pages on the disk.
Paging errors are generated for each memory page.
The virtual memory system encounters a paging error and schedules pagins (page calling). These pages are verified by reading content from the disk.
Once pageins are completed, the file system breaks down the original data to extract the requested file content or attribute information.
Note that the data in this file system will be cached like other memory pages. In subsequent I/O requests, some or all file data is still stored in the physical memory and can be reused directly without re-reading from the disk.
File lock
File locking is a mechanism in which a process can prevent other processes from accessing a file or restrict other processes from accessing the file. Although the name is "file lock", it means to lock the entire file (often done ). Locking can usually be performed at a more fine-grained level. As the granularity drops to the byte level, the file area is usually locked. The lock is associated with a specific file, starting from the specified byte location of the file and running to the specified byte range. This is important because it allows multiple processes to collaborate to access a specific area of a file without interfering with other processes to operate elsewhere in the file.
File locks can be shared or exclusive. Multiple Shared locks can be valid in the same file region at the same time. On the other hand, the exclusive lock requires no other locks to be valid for the requested region.
Stream I/O
Not all I/O functions are block-oriented. There is also stream I/O, which is the prototype of the pipeline and must access the bytes of the I/O data stream in sequence. Common data streams include TTY (console) devices, print ports, and network connections.
Data streams are generally slow but not necessarily slower than block devices, providing intermittent input. Most operating systems are allowed to work in non-blocking mode. A process is allowed to check whether the input of the data stream is available without blocking when it is unavailable. This type of management allows processes to process input when input arrives, and other functions can be executed when the input stream is idle.
More advanced than the non-blocking mode is the conditional selection ). It is similar to the non-blocking mode (and usually based on the non-blocking mode), but reduces the burden on the operating system to check whether the stream is ready. The operating system can be notified to observe the stream set and return the prepared command to the process. This capability allows a process to reuse multiple active streams using common code and a single thread by taking advantage of the preparation information returned by the operating system. This method is widely used in network servers to process a large number of network connections. Preparation and selection are crucial for capacity expansion.
So far, there are a lot of technical terms for this very complicated question.
Java I/O operations
I. Overview
Java IO supports java. classes and interfaces under the I/O package are completed in java. the I/O package mainly includes two types of io streams: input and output. Each input/output stream can be divided into two categories: byte stream and merge stream. Since JDK1.4, Java has provided a series of new APIs in the java. nio package. Through java. nio, the program can perform input and output operations more efficiently.
II. Java I/O class and interface
File Class
The File class directly processes files and File systems. It does not specify how to obtain information or save the information to a File. It only describes the attributes of the File. The File object is used to obtain or operate information associated with the disk File, such as the access permission, time, date, and directory path. You can also view the sub-directory hierarchy.
The following constructor can be used to create a File object:
Constructor summary
File (File parent, String child)
Creates a new File instance based on the abstract path name and child path name string of the parent.
File (String pathname)
Create a new File instance by converting a given path name string to an abstract path name.
File (String parent, String child)
Create a new File instance based on the parent path name string and the child path name string.
File (URI uri)
Create a new file instance by converting the given File: URI into an abstract path name.
The File class defines many methods for obtaining the standard attributes of a File object.
Public class Demo
{
Public static void main (String [] args)
{
File f = new File ("D: // hello. java ");
System. out. println (f. getParent (); // returns the path string of the abstract path name parent directory. If this path name does not specify the parent directory, null is returned.
System. out. println (f. getName (); // return the name of the file or directory represented by the abstract path name.
System. out. println (f. exists (); // test whether the file or directory represented by this abstract path name exists.
System. out. println (f. getAbsoluteFile (); // return the absolute path name form of this abstract path name.
System. out. println (f. getAbsolutePath (); // return the standard path name string of this abstract path.
System. out. println (f. getPath (); // Convert the abstract path name to a path name string
System. out. println (f. hashCode (); // calculate the hash code of this abstract path name
System. out. println (f. length (); // return the length of the file represented by the abstract path name.
System. out. println (f. list (); // returns a string array that specifies the files and directories in the directories represented by this abstract path.
System. out. println (f. mkdir (); // create the directory specified by this abstract path
}
}
2. Stream type
In Java, different input and output sources are abstracted as "streams", which allow? Java programs access different input and output sources in the same way.
Byte stream class: provides a rich environment for processing IO targeting bytes. The top class is InputStream and OutputStream, both of which are abstract classes.
Byte stream class: the byte stream class cannot process Unicode characters. The data unit of the operation is character, and the top class is Reader and Writer.
The functions of the byte stream class are basically the same as those of the bytes stream class, but the data units for operations are different. InputStream and Reader both abstract the data into a pipe, and the program can read () the method extracts a "Water Drop" each time. You can also read multiple "water drops" using the read (char [] cbuf) method. The program uses read () the method returns-1 to determine whether the input stream ends.
For example, to read a file, count the number of characters in the file:
Public class FileDemo
{
Public static void main (String [] args)
{
Int B = 0;
Try
{
FileInputStream in = null;
In = new FileInputStream ("D: \ a.txt ");
Long num = 0;
While (B = in. read ())! =-1)
{
System. out. print (char) B );
Num ++;
}
In. close ();
System. out. println (num );
}
Catch (FileNotFoundException e)
{
E. printStackTrace ();
}
Catch (IOException e)
{
E. printStackTrace ();
}
}
}
The FileInputStream class creates an InputStream that can be used to read files from files.
Eg. Copy the content of one file to another:
Public class FileOutStream
{
Public static void main (String [] args)
{
Int B = 0;
Try
{
FileInputStream in = new FileInputStream ("D: \ Eclipse \ workSpace \ day_041602 \ src \ day_041602 \ TestMain. java ");
FileOutputStream out = new FileOutputStream ("D: \ hello. java ");
While (B = in. read ())! =-1)
{
Out. write (B );
}
In. close ();
Out. close ();
System. out. println ("execution completed ");
}
Catch (FileNotFoundException e)
{
// Catch block automatically generated by TODO
E. printStackTrace ();
} Catch (IOException e)
{
// Catch block automatically generated by TODO
E. printStackTrace ();
}
}
}
BufferedInputStream, BufferedOutputStream, BufferedReader, and BufferedWriter are called buffer streams. They increase performance by buffering input and output.
For example, enter 100 random numbers in the hello. java text and display them on the screen:
Public class BufferWriterDemo
{
Public static void main (String [] args)
{
Try
{
String s;
BufferedWriter bw = new BufferedWriter (new FileWriter ("D :\\ hello. java "));
BufferedReader br = new BufferedReader (new FileReader ("D: \ hello. java "));
For (int I = 0; I <100; I ++)
{
S = String. valueOf (Math. random (); // Generate a random number
Bw. write (s); // write to the hello. java file
Bw. newLine (); // write a line break
}
Bw. flush (); // refresh the buffer
While (s = br. readLine ())! = Null) // read a text line
{
System. out. println (s );
}
Bw. close ();
Br. close ();
}
Catch (IOException e)
{
// Catch block automatically generated by TODO
E. printStackTrace ();
}
}
}
III. NIO
1. Overview
NIO uses the memory ing method to process input and output, and maps a part of a file or file to the memory, so that the file can be accessed just like the memory.
Related packages include: java. nio. channels Package: mainly contains classes related to Channel and Selector. java. nio. charset package: mainly contains classes related to character sets.
NIO is based on two basic elements: buffer and channel. The buffer zone can accommodate data and open connections to the I/O devices of the Channel team. In general, if you use the NIO system, you need to obtain the I? O a channel of the device and a buffer that holds data. Then, you can operate on the buffer and input and output data at will. In addition, NIO provides Charset classes for ing Unicode strings into byte sequences and inverse ING operations, as well as Selector classes that support non-blocking input and output.
2. Buffer Zone
Buffer can be understood as a container. Its essence is an array. All objects sent to the Channel must be put in the buffer first, the data read from the channel must also be read to the buffer first.
Buffer has three important parameters:
Capacity: indicates the maximum storage capacity of the Buffer.
Limit: The first buffer Location Index that should not be read or written
Position: used to specify the index of the next buffer location that can be read or written
There is also an optional mark that allows the program to direct position to the mark. The location is as follows:
Each time a piece of data is put, position moves one bit backward. When the Buffer loads data, call the flip method, set limit to position, and set position to 0, in this way, the read data from the Buffer always starts from 0. After the Buffer output data is complete, the Buffer calls the clear method, which sets the position to 0 and the limit to capacity, so as to prepare for loading data into the Buffer again. The Buffer also provides put and get methods to put data into the Buffer and read data. It supports both single data access and batch data access.
Eg.
Public class Test
{
Public static void main (String [] args)
{
CharBuffer m = CharBuffer. allocate (8 );
M. put ('A ');
M. put ('B ');
M. put ('C ');
System. out. println ("position:" + m. position ());
System. out. println ("limit:" + m. limit ());
M. flip ();
System. out. println ("First Element" + m. get ());
System. out. println ("second element" + m. get ());
System. out. println ("position:" + m. position ());
}
}
Execution result:
3. Channels
The biggest difference between Channel and traditional InputStream and OutputStream is that it provides a map method through which a piece of data can be directly mapped to the memory.
Channel is an interface that provides FileChannel and other implementation classes for this interface. All channels return corresponding channels through the getChannel methods of InputStream and OutputSteam on traditional nodes.
The three most common methods in a Channel are map, read, and write. Here, map maps part or all of the data corresponding to the Channel to ByteBuffer. The read or write method has a series of overloaded forms for reading data.
Eg.copy the content of welcomeservlet.javato a.txt and print the content on the console.
Public class FileChannelTest
{
Public static void main (String [] args)
{
FileChannel inChannel = null;
FileChannel outChannel = null;
FileChannel randomChannel = null;
File f = new File ("D: // WelcomeServlet. java ");
Try
{
FileInputStream fs = new FileInputStream (f );
InChannel = fs. getChannel ();
MappedByteBuffer buffer = inChannel. map (FileChannel. MapMode. READ_ONLY, 0, f. length (); // map all data in inChannel to ByteBuffer
Charset charset = Charset. forName ("GBK ");
OutChannel = new FileOutputStream ("D: // a.txt"). getChannel ();
OutChannel. write (buffer );
Buffer. clear ();
CharsetDecoder decoder = charset. newDecoder (); // Create a decoder object
CharBuffer charBuffer = decoder. decode (buffer); // use the decoder to convert ByteBuffer to charBuffer
System. out. println (charBuffer); // obtain the corresponding string
}
Catch (FileNotFoundException e)
{
// Catch block automatically generated by TODO
E. printStackTrace ();
}
Catch (IOException e)
{
// Catch block automatically generated by TODO
E. printStackTrace ();
}
}
}