Deep understanding of IO in Java
Introduction:
For programmers, creating a good input/output (I/O) system is a difficult task <Thinking in Java>
The directory view in this article is as follows:
Java IO Overview
A. Common classes in Java IO
B. Class Structure of Java stream classes
1. Concept and function of stream
2. models used by Java IO:
3. IO stream classification
4. Java IO Stream Object
1. input byte stream InputStream
2. Output byte stream OutputStream
3. character input stream Reader
4. character output stream Writer
5. Correspondence between input and output of the livestream
6. byte stream and byte stream conversion
7. Differences between byte streams and byte streams
8. File class
9. RandomAccessFile class
Java IO OverviewTo facilitate understanding and elaboration, we first introduce two images:A. Common classes in Java IO
Five classes and one interface are the most important in the entire Java. io package. Five classes refer to File, OutputStream, InputStream, Writer, and Reader. One interface refers to Serializable. after mastering these core IO operations, I have a preliminary understanding of the IO System in Java.
Java I/O consists of the following layers:
1. Stream part-Main part of IO;
2. Non-streaming part-It mainly contains classes of the secondary stream, such as File, RandomAccessFile, and FileDescriptor;
3. Other classes-- Security-related classes for file reading, such as SerializablePermission and file system classes related to local operating systems, such as FileSystem, Win32FileSystem, and WinNTFileSystem.
The main classes are as follows:
1. File (File features and management): used for describing a File or directory, such as generating a new directory, modifying the File name, deleting the File, and determining the path of the File.
2. InputStream (binary format operation): abstract class, byte-based input operation, is the parent class of all input streams. Defines the common features of all input streams.
3. OutputStream (binary format operation): abstract class. Byte-based output operations. Is the parent class of all output streams. Defines the common features of all output streams.
4. Reader (File Format operation): abstract class, character-based input operation.
5. Writer (File Format operation): abstract class, character-based output operation.
6. RandomAccessFile (random file operation): an independent class that inherits directly to the Object. It has rich functions,Attackers can access (input and output) files from any location..
Architecture of IO stream in Java
B. Class Structure of the Java stream class:
1. Concept and function of streamStream: represents any data source object that can generate data or the receiver object that can accept data. The essence of a stream: Data Transmission abstracts the stream into various types based on the data transmission characteristics, facilitating more intuitive data operations.
Stream Function: Creates a transport channel for the data source and destination.
In Java, the input/output abstraction is called a stream. It is like a pipe that connects two containers. A stream is a set of sequential bytes with a starting point and an ending point. It is a general term or abstraction for data transmission. That is, data transmission between two devices is called a stream.
2. models used by Java IO
The I/O model of Java is well designed. It uses the Decorator mode and divides streams by function. You can dynamically assemble these streams to obtain the functions you need.
For example, if you need a buffer file input stream, FileInputStream and BufferedInputStream should be used in combination.
3. IO stream classification
· Data types can be divided into two types: dense stream and word throttling.
· Input stream and output stream based on different data flows
· Classification by data source (destination:
1. File: FileInputStream, FileOutputStream, FileReader, and FileWriter
2. byte []: ByteArrayInputStream, ByteArrayOutputStream
3. Char []: CharArrayReader, CharArrayWriter
4. String: StringBufferInputStream, StringReader, StringWriter
5. network data streams: InputStream, OutputStream, Reader, and Writer
Traffic and word throttling
The data in the stream sequence can be either the raw binary data that has not been processed, or the specific data that has been encoded to conform to certain formats. Therefore, Java streams are divided into two types:
1)Byte stream:The smallest data unit in a data stream is byte.
2)Ghost stream:The smallest data unit in a data stream is a character. The characters in Java are Unicode encoded and one character occupies two bytes.
History stream:In Java, the character adopts the Unicode standard. A character is a 16-bit character, that is, a character is expressed in two bytes. To this end, JAVA introduces Stream processing characters. Because of the differences in data encoding, stream objects that perform efficient operations on characters are available. In essence, when reading data based on byte streams, the specified code table is checked.
Input stream and output stream
Streams are divided into input streams and output streams based on different data input and output directions.
1) input stream
The program reads the data source from the input stream. Data sources include external sources (keyboards, files, networks, etc ...), That is, the communication channel that reads the data source into the program
2) output stream
The program writes data to the output stream. Output Data in the program to the outside world (display, printer, file, network ...) .
The purpose of data flow is to make the output input independent from the device.
The Input Stream does not care about the device (keyboard, file, network) from which the data source comes ).
The output stream does not care about the device (keyboard, file, network) that the data is intended ).
3) Features
Compared with the program, the output stream writes data to the storage media or data channel, while the input stream reads data from the storage media or data channel. Generally, there are the following stream features:
1. Data written to the output stream is first read by the input stream.
2. sequential access: you can write a string of bytes to the stream one by one. During reading, a string of bytes will also be read in the write order, and data in the middle cannot be randomly accessed. (RandomAccessFileAttackers can access (input and output) files from any location.)
3. Read-only or write-only. Each stream can only be an input stream or an output stream. It cannot have two functions at the same time. The input stream can only perform read operations and write operations on the output stream. In a data transmission channel, if you want to write data and read data, you must provide two streams respectively.
4. Java IO Stream Object
1. input byte stream InputStream
The inheritance diagram of input byte streams in IO is visible, as shown in the following figure:
1. InputStream is the parent class of all input byte streams. It is an abstract class.
2. ByteArrayInputStream, StringBufferInputStream (StreamBufferInputStream), and FileInputStream are three basic media streams that read data from Byte arrays, StringBuffer, and local files respectively.
3. PipedInputStream reads data from the pipeline shared with other threads.
4. ObjectInputStream and all the sub-classes of FilterInputStream are decorative streams (the main character of the decoration mode ).
Three basic read methods in InputStream
Abstract int read (): reads a byte of data and returns the read data. If-1 is returned, the data is read to the end of the input stream.
Intread (byte []? B): Read data into a byte array and return the actual number of bytes read. If-1 is returned, it indicates that the input stream is read to the end.
Intread (byte []? B, int? Off, int? Len): reads data into a byte array and returns the actual number of bytes read. If-1 is returned, it indicates that the input stream is read to the end. Off specifies the starting offset position for storing data in array B, and len specifies the maximum number of bytes to read.
Stream end judgment: when the return value of the read () method is-1, when the return value of readLine () is null.
Other methods
Long skip (long? N): Skips n bytes in the input stream and returns the number of bytes actually skipped.
Int available (): the number of bytes that can be read without blocking.
Void close (): closes the input stream and releases system resources related to the stream.
Voidmark (int? Readlimit): place a flag at the current position of the input stream. If the number of bytes read exceeds the value set by readlimit, the stream ignores this flag.
Void reset (): returns to the previous mark.
BooleanmarkSupported (): Tests whether the current stream supports the mark and reset methods. If yes, true is returned. Otherwise, false is returned.
2. Output byte stream OutputStream
The inheritance diagram of the output byte stream in IO is visible, as shown in the following figure:
1. OutputStream is the parent class of all output byte streams. It is an abstract class.
2. ByteArrayOutputStream and FileOutputStream are two basic media streams, which write data to Byte arrays and local files respectively. PipedOutputStream is used to write data to pipelines shared with other threads.
3. ObjectOutputStream and all the sub-classes of FilterOutputStream are decorative streams.
Three basic write methods in outputStream
Abstract void write (int? B): Write a byte to the output stream.
Void write (byte []? B): write all the bytes in array B to the output stream.
Void write (byte []? B, int? Off, int? Len): Write len bytes starting from offset off in array B to the output stream.
Other methods
Void flush (): refreshes the output stream and forces the output bytes in the buffer zone to be written.
Void close (): closes the output stream and releases system resources related to the stream. 3. character input stream Reader
The above inheritance graph shows that:
1. Reader is the parent class of all input streams. It is an abstract class.
2. CharReader and StringReader are two basic media streams that read data from Char arrays and strings respectively. PipedReader reads data from pipelines shared with other threads.
3. BufferedReader is obviously a decorator, which and its sub-classes are responsible for decorating other Reader objects.
4. FilterReader is the parent class of all custom decorative streams. Its subclass PushbackReader is used to decorate the Reader object and adds a row number.
5. InputStreamReader is a bridge between the byte stream and the upstreaming stream. It converts byte streams into upstreaming streams. FileReader can be said to be a commonly used tool class to achieve this function. In its source code, the FileInputStream is obviously used as a Reader method. We can get some tips from this class. The usage and usage of each class in Reader are basically the same as that in InputStream. There will be a ing between Reader and InputStream.
Main Methods:
(1) publicintread () throwsIOException; // read a character and return the read character
(2) publicintread (charcbuf []) throwsIOException;/* read a series of characters to the array cbuf [], and return the number of characters actually read */
(3) publicpolicactintread (charcbuf [], 0000ff, intlen) throwsIOException;
/* Read len characters and store them from the subscript off of the array cbuf []. The returned value is the number of characters actually read. This method must be implemented by sub-classes */
4. character output stream Writer
The preceding graph shows that:
1. Writer is the parent class of all output streams. It is an abstract class.
2. CharArrayWriter and StringWriter are two basic media streams that write data to Char arrays and strings respectively. PipedWriter writes data to pipelines shared with other threads,
3. BufferedWriter is a decorator that provides the buffer function for Writer.
4. PrintWriter and PrintStream are extremely similar in functionality and usage.
5. OutputStreamWriter is a bridge between conversion from OutputStream to Writer. Its subclass FileWriter is actually a specific class that implements this function (you can study SourceCode ). Functions and usage are similar to those of OutputStream.
Main Methods:
(1) publicvoidwrite (intc) throwsIOException; // write the low 16 bits of integer c to the output stream
(2) publicvoidwrite (charcbuf []) throwsIOException; // write the character array cbuf [] to the output stream
(3) publicpolicactvoidwrite (charcbuf [], 0000ff, intlen) throwsIOException; // write the len characters starting from the position where the index is off in the character array cbuf [] to the output stream.
(4) publicvoidwrite (Stringstr) throwsIOException; // write the characters in the str string to the output stream.
(5) publicvoidwrite (Stringstr, 0000ff, intlen) throwsIOException; // write the len characters starting from the index off in the str string to the output stream.
5. Correspondence between input and output of byte streams
In the figure, the blue part is the main corresponding part, and the red part is the non-corresponding part. From the figure above, we can see that the byte stream in JavaIO is extremely symmetric. "Exist and make sense." Let's look at several classes that are not symmetric in these byte streams!
1. lineNumberInputStream obtains the corresponding row number when it reads data from the stream. When and where the branch is determined by the change class, there is not such a line number in the original. There is no corresponding part in the output part. We can create a LineNumberOutputStream by ourselves. There will be a baseline line number when we first write data, and a line number will be added to the next line each time we encounter a line change, it looks okay, too. It seems that it is not streaming.
2. The PushbackInputStream function is to view the last byte and put it into the buffer zone if it is not satisfied. It is mainly used in Compiler syntax and lexical analysis. The BufferedOutputStream of the output is almost similar.
3. The StringBufferInputStream has been Deprecated and should not appear in the InputStream part because the String should belong to the range of the hidden stream. It has been deprecated. Of course, it is not necessary for the output part! It is also allowed to exist only to keep the version backward compatible.
4. SequenceInputStream can be considered as a tool class. Two or more input streams are read as one input stream in sequence. It can be removed from the IO package completely without affecting the structure of the IO package, but making it "pure"-pure Decorator mode.
5. PrintStream can also be considered as an auxiliary tool. Data can be written to other output streams, or FileInputStream. The internal implementation is still buffered. Essentially, it is a tool for the comprehensive use of other streams. I/O packages can be kicked out! System. out and System. out are PrintStream instances!
The correspondence between input and output of the livestream
6. byte stream and byte stream conversion
Conversion stream features:
1. It is a bridge between the traffic and the word throttling.
2. You can convert the read byte data to a character using the specified encoding.
3. You can convert the character data to byte by specifying encoding.
When to use a conversion stream?
1. When there is a conversion between byte and character;
2. When the stream operation data needs to be encoded or decoded.
Specific Object embodiment:
Conversion stream: In IO, another type of conversion stream exists. byte streams can be converted into bytes streams.
1. InputStreamReader:Byte to character Bridge
2.OutputStreamWriter:Character to byte Bridge
OutputStreamWriter (OutStreamout): outputs byte streams as bytes streams.
InputStreamReader (InputStreamin): Inputs byte streams in bytes streams.
These two stream objects are members of the character system. They have a conversion function, and they are character streams. Therefore, byte stream objects need to be input during construction.
7. Differences between byte streams and byte streams (important)
Differences between byte stream and byte stream(For details, see ttp: // blog.csdn.net/qq_25184739/article/details/51203733)
There is no buffer for throttling, And the swap stream is output to the buffer. Therefore, when the byte stream does not call the colse () method, the information has been output, and the bytes stream outputs the information only when the close () method is called to close the buffer. To output information when the compaction stream is not closed, you need to manually call the flush () method.
· Different read/write units: byte streams are measured in 8 bits and byte streams are measured in characters. You may read multiple bytes at a time based on the ing characters in the code table.
· Different processing objects: byte streams can process all types of data (such as slice and avi), while byte streams can only process character-type data.
Conclusion: as long as the plain text data is processed, the use of the plain stream is preferred. In addition, byte streams are used.
8. Non-streaming File class-File class
In terms of definition, the File class is the direct subclass of objects, and it inherits the Comparable interface to sort arrays.
File Operations include File creation, deletion, renaming, paths, and creation time. The following are common functions for File operations.
A File class is an object that encapsulates files and folders in a File system. You can use the object idea to operate files and folders. File class stores various metadata information about a File or directory, including the File name, File length, last modification time, whether the File is readable, and obtaining the path name of the current File, determine whether a specified file exists, obtain the file list in the current directory, and create or delete files and directories.
The File class provides three different constructors to flexibly receive File and directory name information with different parameters.
Constructor:
1) File (String pathname)
For example, File f1 = new File ("FileTest1.txt"); // create a File object f1,f1the File specified is the File test1.txt created under the current directory.
2) File (String parent, String child)
For example, File f2 = new File ("D: \ dir1", "FileTest2.txt"); // Note: The D: \ dir1 directory must exist in advance; otherwise, an exception occurs.
3) File (File parent, String child)
Example: File f4 = new File ("\ dir3 ");
File f5 = new File (f4, "FileTest5.txt"); // If the \ dir3 directory does not exist, use f4.mkdir () to create
Once a File object corresponding to a disk File or directory is created, you can call it to obtain the attributes of the File or directory.
1) public boolean exists () to determine whether a file or directory exists
2) public boolean isFile () determines whether it is a file or a directory.
3) public boolean isDirectory () determines whether it is a file or a directory.
4) public String getName () returns the file name or directory name.
5) public String getPath () returns the path of the file or directory.
6) public long length () Get the object length
7) public String [] list () stores all file names in the directory in the String array and returns the results.
The File class also defines some methods for managing and operating files or directories. Common methods include:
1) public boolean renameTo (File newFile); rename the File
2) public void delete (); delete an object
3) public boolean mkdir (); create a directory
Example:
1. public class FileDemo1 { 2. public static void main(String[] args) { 3. File file = new File("D:" + File.separator + "test.txt"); 4. if (file.exists()) { 5. file.delete(); 6. } else { 7. try { 8. file.createNewFile(); 9. } catch (IOException e) { 10. // TODO Auto-generated catch block 11. e.printStackTrace(); 12. } 13. } 14. } 15. }
9. RandomAccessFile class
This object is not a member of the stream system. It encapsulates the byte stream and a buffer (character array) to operate data in the character array through internal pointers. Features:
1. This object can only operate on files. Therefore, the constructor receives two types of parameters: a. String File path and B. File object.
2. This object can read and write files. You can specify the operation mode (r, rw) when instantiating objects)
Note: When the object is instantiated, if the file to be operated does not exist, it will be automatically created. If the file exists and the write data is not specified, it will be written from the beginning, that is, overwrite the original content.It can be used to download data in multiple threads or write data to files simultaneously.
10. IO support for the System class
For some frequent device interactions, the Java language system has three stream objects that can be directly used:
· System. in (standard input), usually representing keyboard input.
· System. out (standard output): usually written to the monitor.
· System. err (standard error output): usually written to the monitor.
Standard I/O
Java programs can exchange brief information with the outside world through command line parameters. It also specifies the way to exchange information with standard input and output devices, such as keyboards and monitors. Files can exchange information in any form with the outside world.
1. Command Line Parameters
public class TestArgs { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "] is <" + args[i] + ">"); } } }
Run the following command: java Java C VB
Running result:
args[0] is
args[1] is
args[2] is
2. Standard input and output data streams
Java. lang. System:
Java. lang. system public final class System extends Object {static PrintStream err; // standard error stream (output) static InputStream in; // standard input (keyboard input stream) static PrintStream out; // standard output stream (Display output stream )}
Note:
(1) The System class cannot create objects. It can only use three static members of the System class.
(2) Each time the main method is executed, the above three objects are automatically generated.
1) standard output stream System. out
System. out outputs data to the standard output device. The data type is PrintStream. Method:
Void print (parameter)
Void println (parameter)
2) standard input stream System. in
System. in reads data from the standard input device (obtains data from the standard input, usually the keyboard). The data type is InputStream. Method:
Int read () // returns the ASCII code. If the returned value is-1, it indicates that no Bytes have been read.
Int read (byte [] B) // read multiple bytes to buffer B. The returned value is the number of bytes read.
For example:
import java.io.*; public class StandardInputOutput { public static void main(String args[]) { int b; try { System.out.println("please Input:"); while ((b = System.in.read()) != -1) { System.out.print((char) b); } } catch (IOException e) { System.out.println(e.toString()); } } } Wait for the keyboard to input and print the following content:
3) standard error stream
System. err outputs a standard error. The data type is PrintStream. See the API for details.
The standard output calls the println method through System. out to output parameters and wrap them. The print method outputs parameters but does not wrap them. Both println and print methods have implemented multiple methods for outputting basic data types through overload, including the output parameter types: boolean, char, int, long, float, and double. At the same time, the output parameters of char [], String, and Object types are also overloaded. The print (Object) and println (Object) Methods call the toString method of the parameter Object at runtime.
Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; public class StandardInputOutput {public static void main (String args []) {String s; // create a buffer reader to read data from the keyboard row by row. InputStreamReader ir = new InputStreamReader (System. in); BufferedReader in = new BufferedReader (ir); System. out. println ("Unix: ctrl-d or ctrl-c Exit" + "\ nWindows: ctrl-z exit"); try {// read a row of data, standard output to display In. readLine (); // If an I/O error occurs when the readLine () method is running, an IOException exception is thrown. while (s! = Null) {System. out. println ("Read:" + s); s = in. readLine ();} // close the buffer reader in. close ();} catch (IOException e) {// Catch any IO exceptions. e. printStackTrace ();}}}
In Java, the steps for using byte streams are basically the same as those for using a streaming. Taking the input stream as an example, first create a stream object related to the data source, and then use the stream object method to input data from the stream, finally, execute the close () method to close the stream.
Additional:
Subclass of the IOException class
1. public class EOFException: This type of exception is thrown when the file or input stream tail is not properly reached.
2. public class FileNotFoundException: The exception thrown when the file cannot be found.
3. public class InterruptedIOException: This type of exception is thrown when I/O operations are interrupted.