The input and output functions of the Java language are very powerful and flexible. The disadvantage is that it seems that the input and output code is not very concise, Because you often need to wrap many different objects. In Java class libraries, the I/O part of the content is very large, because it involves a wide range of fields: standard input and output, file operations, network data streams, string streams, object stream, zip file stream .... the purpose of this article is to give a brief introduction.
Stream is a very visual concept. When the program needs to read data, it will open a stream to the data source, which can be a file, memory, or network connection. Similarly, when the program needs to write data, it will open a stream to the destination. At this time, you can imagine that the data is like a "stream" in it, such:
In Java, streams are divided into two types: byte streams and merge streams, which are represented by four abstract classes respectively (each type of stream includes two types of input and output, so there are four in total ): inputstream, outputstream, reader, and writer. In Java, other diverse stream types are derived from them:
Among them, inputstream and outputstream already exist in earlier Java versions. They are based on byte streams, while reader and writer based on bytes streams are later added as supplements. The above level chart is a basic level system in the Java class library.
In these four abstract classes, inputstream and reader define the same interface:
|
Int read ()
Int read (char cbuf [])
Int read (char cbuf [], int offset, int length) |
The same is true for outputstream and Writer:
|
Int write (int c)
Int write (char cbuf [])
Int write (char cbuf [], int offset, int length) |
These six methods are the most basic. Read () and write () read a byte or a byte array through method overloading.
More flexible and variable functions are extended by their subclasses. After learning about the basic hierarchy of JAVA input and output, this article will give you some examples that can be used repeatedly in the future. The details of all sub-classes and their functions are not discussed in detail.
|
Import java. Io .*;
Public class iostreamdemo {
Public void samples () throws ioexception {
// 1. This is to read a row of data from the keyboard and return a string
Bufferedreader stdin = new bufferedreader (New inputstreamreader (system. In ));
System. Out. Print ("enter a line :");
System. Out. println (stdin. Readline ());
// 2. This is to read data row by row from the file
Bufferedreader in = new bufferedreader (newfilereader ("iostreamdemo. Java "));
String S, S2 = new string ();
While (S = in. Readline ())! = NULL)
S2 + = S + "\ n ";
In. Close ();
// 3. This is to read bytes one by one from a string
Stringreader in1 = new stringreader (S2 );
Int C;
While (C = in1.read ())! =-1)
System. Out. Print (char) C );
// 4. This is to write a string into the file
Try {
Bufferedreader in2 = new bufferedreader (New stringreader (S2 ));
Printwriter out1 = new printwriter (New bufferedwriter (New filewriter ("iodemo. Out ")));
Int linecount = 1;
While (S = in2.readline ())! = NULL)
Out1.println (linecount ++ ":" + S );
Out1.close ();
} Catch (eofexception e ){
System. Err. println ("End of stream ");
}
}
} |
For the above example, we need to explain the following points:
1. bufferedreader is a sub-class of reader. It can buffer data and avoid reading information from physical devices frequently. It has the following constructor:
|
Bufferedreader (Reader in)
Bufferedreader (Reader in, int sz) |
The SZ here specifies the buffer size.
The basic method is as follows:
|
Void close () // close the stream
Void mark (INT readaheadlimit) // mark the current location
Boolean marksupported () // whether tag is supported
Int read () // basic method inherited from Reader
Int read (char [] cbuf, int off, int Len) // basic method inherited from Reader
String Readline () // read a line of content and return it as a string
Boolean ready () // determines whether the stream is ready for reading.
Void reset () // reset to the nearest mark
Long SKIP (long n) // skip reading a specified number of characters |
2. inputstreamreader is a bridge between inputstream and reader. Because system. In is a byte stream, it needs to be packaged and then changed to a bytes stream for bufferedreader.
3. printwriter out1 = new printwriter (New bufferedwriter (newfilewriter ("iodemo. Out ")));
This statement represents a feature of the JAVA input/output system. for a specific purpose, several layers need to be packaged. First, the output destination is the file iodemo. therefore, filewriter is encapsulated at the innermost layer to create an output file stream. Next, we want this stream to be buffered. Therefore, bufferedwriter is used to package it for the purpose. Finally, we need to format the output result, so we put the printwriter package in the outermost layer.
Java provides such a function to turn a standard input/output stream. That is to say, we can set another stream as a standard input or output stream. See the following example:
|
Import java. Io .*;
Public class redirecting {
Public static void main (string [] ARGs) throws ioexception {
Printstream console = system. out;
Bufferedinputstream in = new bufferedinputstream (New fileinputstream ("redirecting. Java "));
Printstream out = new printstream (New bufferedoutputstream (New fileoutputstream ("test. Out ")));
System. setin (in );
System. setout (out );
Bufferedreader BR = new bufferedreader (newinputstreamreader (system. In ));
String S;
While (S = Br. Readline ())! = NULL)
System. Out. println (s );
Out. Close ();
System. setout (console );
}
} |
The static method of Java. Lang. System
|
Static void setin (inputstream in)
Static void setout (printstream out) |
It is convenient to redefine the standard input/output stream. For example, there are many results in a program, and sometimes the results may even be displayed on pages, which makes it difficult to view the results, you can define a standard output stream as a file stream. After the program runs, you can open the corresponding file to view the results, which is much more intuitive.
Java streams have another important purpose, that is, serialization of objects using object streams. The following describes the problem.
When a program runs, the variable data is stored in the memory. Once the program ends, the data will not be saved. One solution is to write the data to a file, java provides a mechanism to write the objects in the program to a file, and then read the objects from the file and recreate them. This is the so-called Object serialization java. It is mainly used for RMI (Remote Method Invocation) and Java Bean. However, it is also a useful technology in common applications.
All objects that require Object serialization must first implement the serializable interface. The following is an example:
|
Import java. Io .*;
Import java. util .*;
Public class logon implements serializable {
Private date = new date ();
Private string username;
Private transient string password;
Logon (string name, string PWD ){
Username = Name;
Password = PWD;
}
Public String tostring (){
String Pwd = (Password = NULL )? "(N/a)": password;
Return "Logon info: \ n" + "username:" + username + "\ n Date:" + date + "\ n password:" + PWD;
}
Public static void main (string [] ARGs) throws ioexception, classnotfoundexception {
Logon A = new Logon ("Morgan", "morgan83 ");
System. Out. println ("Logon A =" + );
Objectoutputstream o = new objectoutputstream (newfileoutputstream ("Logon. Out "));
O. writeobject ();
O. Close ();
Int seconds = 5;
Long T = system. currenttimemillis () + secondds * 1000;
While (system. currenttimemillis () <t );
Objectinputstream in = new objectinputstream (newfileinputstream ("Logon. Out "));
System. Out. println ("Recovering object at" + new date ());
A = (logon) in. readobject ();
System. Out. println ("Logon A =" + );
}
} |
Logon is a class that records logon information, including the user name and password. First, it implements the interface serializable, which indicates that it can be serialized. Then in the main method, objectoutputstream o = newobjectoutputstream (New fileoutputstream ("logon. "Out"). Create an object output stream to wrap a file stream, indicating that the object serialization destination is the file logon. out. Then, use the writeobject method to start writing. Objectinputstream in = new objectinputstream (newfileinputstream ("logon. out "); creates an object input stream to use the file stream logon. the out parameter is used to call the readobject method.
It should be noted that the magic of Object serialization is that it creates an object network and includes all the objects referenced in the objects to be serialized and writes them to the file, even more importantly, if you serialize several objects at a time, the same content will be shared and written to them. This is indeed a very good mechanism. It can be used for deep copy.
The keyword transient indicates that the current content will not be serialized. For example, the password in the example needs to be kept confidential, so it is not written into the file.
I will briefly introduce the input and output functions of Java. The purpose of this article is just to provide a good start and hope to give you a basic understanding of the JAVA input and output stream.
For the commonly used GBK, English occupies 1 byte and Chinese represents 2
For UTF-8, English is 1, Chinese is 3
For Unicode, both Chinese and English
Java stream operations can be divided into byte streams and byte streams.
1. byte stream
All read Operations inherit from a common superclass java. Io. inputstream class.
All write operations inherit from a common superclass java. Io. outputstream class.
Both inputstream and outputstream are abstract classes.
Inputstream has six low-level input streams:
Low-level stream
Stream usage
Bytearrayinputstream
Read data bytes from memory array
Fileinputstream
Read data bytes from the local file system
Pipedinputstream
Read data bytes from the thread Pipeline
Stringbufferinputstream
Reads data bytes from a string.
Sequenceinputstream
Reads data bytes from two or more low-level streams, and transfers data from one stream to another when it reaches the end of the stream.
System. In
Read data bytes from the user Console
Inputstream also has a subclass: the filter stream java. Io. filterinputstream. The filter stream encapsulates the basic stream for more convenient usage.
The construction method of the filterinputstream class is filterinputstream (inputstream). An input stream filter is created on the specified input stream.
Common subclasses of filterinputstream are as follows:
Filter input stream
Stream usage
Bufferedinputstream
Access data by the buffer to improve efficiency
Datainputstream
Reads basic data types from the input stream, such as int, float, double, or even a line of text.
Linenumberinputstream
Maintain a counter Based on the line terminator of the translation. The counter indicates the row being read.
Pushbackinputstream
Data bytes can be pushed back to the first part of the stream.
Outputstream (omitted)
The structure of outputstream is basically the same as that of inputstream.
2. Ghost stream
Note: It was introduced in jdk1.1, And the byte stream above was introduced in jdk1.0. When it is used to process text data, it is better to select the limit stream than the word throttling. However, developers who only use the basic data type can continue to use byte streams.
All read Operations inherit from a common superclass java. Io. Reader class.
All write operations inherit from a common superclass java. Io. Writer class.
Reader and writer are also abstract classes.
The common subclass of reader is as follows:
Low-level Reader
Stream usage
Chararrayreader
Read data from character array
Inputstreamreader
Filereader (subclass of inputstreamreader)
Read character sequences from local file systems
Stringreader
Read character sequences from strings
Pipedreader
Read character sequences from thread Pipelines
Inputstreamreader:
Inputstreamreader reads data from the input stream and connects the input stream to the reader. For example:
New inputstreamreader (system. In)
Constructor:
Inputstreamreader (inputstream)
Use the default character encoding method to create an inputstreamreader.
Inputstreamreader (inputstream, string)
Create an inputstreamreader using the named character encoding method.
Common filter readers:
Filter Reader
Stream usage
Bufferedreader
Buffer Data Access to improve efficiency
Linenumberreader (subclass of bufferedreader)
Maintain a counter that indicates the row being read.
Filterreader (abstract class)
Provides a class that can be extended when a filter is created.
Pushbackreader (subclass of filterreader)
Allow text data to be pushed back to the reader stream
All these filter readers can pass in a reader as a constructor parameter.
Writer (omitted)
The structure of writer is basically the same as that of reader.
Byte streams are the most basic, and forward streams are proposed to process characters.
New bufferedreader (New inputstreamreader (client. getinputstream (); explanation:
Client. getinputstream () is a byte stream;
Inputstreamreader converts byte streams into bytes streams;
Bufferedreader caches the primary stream so that you can directly read a row using methods such as Readline.
Java provides a java. Io package dedicated to the input and output functions, including:
Inputstream, outputstream, reader, writer
Inputstream and outputstream are designed for byte streams and are mainly used to process byte or binary objects,
Reader and writer. These two are designed for the character stream (one character occupies two bytes) and are mainly used to process characters or strings.
The byte stream processing unit is two bytes of Unicode characters, operating characters, character arrays or strings respectively, while the byte stream processing unit is one byte, operating byte and byte array. Therefore, the compaction stream is a character that is converted from a Java virtual machine to a Unicode Character in two bytes. Therefore, it is highly supported by many languages! For audio files, images, and songs, use text to reduce the cost. For Chinese (text) files, use text to improve the streaming speed.
All files are stored in bytes. What is stored on the disk is not the character of the file, but the characters are first encoded into bytes, and then stored on the disk. When reading a file (especially a text file), it is also a byte read to form a byte sequence.
Byte streams can be used for any type of objects, including binary objects. The byte stream can only process characters or strings. 2. byte stream provides the ability to process any type of Io operations, but it cannot directly process Unicode characters, while the bytes stream can
Byte streams are the most basic. All inputstrem and outputstream subclasses are used to process binary data. They are processed by byte, but in reality a lot of data is text, the concept of upstreaming is also proposed, which is handled by the virtual machine's encode, that is, the character set conversion between the two is associated through inputstreamreader and outputstreamwriter, in fact, byte [] and string are used to associate the problem of Chinese Characters in actual development. In fact, these problems are caused by inconsistent conversion between the primary stream and the word throttling.