A thorough understanding of Java I/O Systems
I. Input and Output
1. Stream represents any data source capable of producing data or any receiving source capable of receiving data. In Java I/O, all streams (including input and out stream) have two types:
1.1 byte-oriented stream
A byte-oriented stream that reads or writes information to a stream in bytes. Byte-oriented streams include the following types:
1) input stream:
1) bytearrayinputstream: uses a buffer in the memory as an inputstream.
2) stringbufferinputstream: Use a String object as inputstream.
3) fileinputstream: uses a file as inputstream to read the file.
4) pipedinputstream: implements the pipe concept and is mainly used in the process.
5) sequenceinputstream: combines multiple inputstreams into one inputstream.
2) Out stream
1) bytearrayoutputstream: stores information in a buffer zone in the memory.
2) fileoutputstream: stores information in a file.
3) pipedoutputstream: implements the concept of pipe, which is mainly used in the process.
4) sequenceoutputstream: combines multiple outstreams into one outstream.
1.2 Unicode Character-oriented stream
A Unicode-oriented stream that reads or writes information from a stream in units of Unicode characters. Unicode-oriented streams include the following types:
1) input stream
1) chararrayreader: corresponds to bytearrayinputstream
2) stringreader: corresponds to stringbufferinputstream
3) filereader: corresponds to fileinputstream
4) pipedreader: corresponds to pipedinputstream.
2) Out stream
1) chararraywrite: corresponds to bytearrayoutputstream
2) stringwrite: no corresponding byte-oriented stream
3) filewrite: corresponds to fileoutputstream
4) pipedwrite: corresponds to pipedoutputstream
Character-oriented stream basically corresponds to a byte-oriented stream. The functions of the two corresponding classes are the same, and the words are different in operation. For example, chararrayreader and bytearrayinputstream both use a buffer in the memory as inputstream. The difference is that the former reads a byte of information from the memory each time, the latter reads one character from the memory each time.
1.3 conversions between two non-existing stream types
Inputstreamreader and outputstreamreader: convert a byte-oriented stream into a character-oriented stream.
2. Add attributes to stream
2.1 role of "adding attributes for stream"
Using the I/O APIs in Java described above, we can complete any operation we want to complete. However, through the sub-classes of filterinputstream and filteroutstream, we can add attributes for stream. The following is an example to illustrate the role of this function.
If we want to write data to a file, we can do this:
Fileoutstream FS = new fileoutstream(‑test.txt ");
Then, you can use write(writable writable) to write data to the test.txt file. However, if we want to implement the "First cache the data to be written into the file into the memory, then write the data in the cache into the file" function, none of the above APIs can meet our needs. However, we can use the sub-classes of filterinputstream and filteroutstream to add the required functions for fileoutstream.
2.2 various types of filterinputstream
2.2.1 encapsulate byte-oriented inputstream
1) datainputstream: reads data of basic types (such as int and char) from stream.
2) bufferedinputstream: Buffer
3) linenumberinputstream: records the number of rows in the input stream. You can call getlinenumber () and setlinenumber (INT)
4) pushbackinputstream: rarely used and generally used for Compiler Development
2.2.2 encapsulate character-oriented inputstream
1) there is no class corresponding to datainputstream. Unless you use bufferedreader when using Readline (), use datainputstream
2) bufferedreader: corresponds to bufferedinputstream
3) linenumberreader: corresponds to linenumberinputstream
4) pushbackreader: corresponds to pushbackinputstream
2.3 various types of filteroutstream
2.2.3 encapsulate byte-oriented outputstream
1) dataioutstream: outputs basic data types (such as int and char) to stream.
2) bufferedoutstream: Buffer
3) printstream: produce formatted output
2.2.4 character-oriented outputstream Encapsulation
1) bufferedwrite: corresponds
2) printwrite: corresponds
3. randomaccessfile
1) You can use the randomaccessfile object to read and write files.
2) when an object is generated, you can specify the nature of the file to be opened: R, read-only; W, write-only; RW, read/write
3) You can directly jump to the specified position in the file.
4. An example of an I/O Application
Import java. Io .*;
Public class testio {
Public static void main (string [] ARGs)
Throws ioexception {
// 1. read data from a file in behavior units
Bufferedreader in =
New bufferedreader (
New filereader ("F: // nepalon // testio. Java "));
String S, S2 = new string ();
While (S = in. Readline ())! = NULL)
S2 + = S + "/N ";
In. Close ();
// 1b. Receive keyboard input
Bufferedreader stdin =
New bufferedreader (
New inputstreamreader (system. In ));
System. Out. println ("enter a line :");
System. Out. println (stdin. Readline ());
// 2. read data from a string object
Stringreader in2 = new stringreader (S2 );
Int C;
While (C = in2.read ())! =-1)
System. Out. println (char) C );
In2.close ();
// 3. Extract formatted input from memory
Try {
Datainputstream in3 =
New datainputstream (
New bytearrayinputstream (s2.getbytes ()));
While (true)
System. Out. println (char) in3.readbyte ());
}
Catch (eofexception e ){
System. Out. println ("End of stream ");
}
// 4. output to file
Try {
Bufferedreader in4 =
New bufferedreader (
New stringreader (S2 ));
Printwriter out1 =
New printwriter (
New bufferedwriter (
New filewriter ("F: // nepalon // testio. Out ")));
Int linecount = 1;
While (S = in4.readline ())! = NULL)
Out1.println (linecount ++ ":" + S );
Out1.close ();
In4.close ();
}
Catch (eofexception ex ){
System. Out. println ("End of stream ");
}
// 5. Data Storage and Restoration
Try {
Dataoutputstream out2 =
New dataoutputstream (
New bufferedoutputstream (
New fileoutputstream ("F: // nepalon // data.txt ")));
Out2 writedouble (3.1415926 );
Out2.writechars ("/nthas was Pi: writechars/N ");
Out2.writebytes ("thas was Pi: writebyte/N ");
Out2.close ();
Datainputstream in5 =
New datainputstream (
New bufferedinputstream (
New fileinputstream ("F: // nepalon // data.txt ")));
Bufferedreader in5br =
New bufferedreader (
New inputstreamreader (in5 ));
System. Out. println (in5.readdouble ());
System. Out. println (in5br. Readline ());
System. Out. println (in5br. Readline ());
}
Catch (eofexception e ){
System. Out. println ("End of stream ");
}
// 6. Operate the file through randomaccessfile
Randomaccessfile Rf =
New randomaccessfile ("F: // nepalon // rtest. dat", "RW ");
For (INT I = 0; I <10; I ++)
RF. writedouble (I * 1.414 );
RF. Close ();
Rf = new randomaccessfile ("F: // nepalon // rtest. dat", "R ");
For (INT I = 0; I <10; I ++)
System. Out. println ("value" + I + ":" + RF. readdouble ());
RF. Close ();
Rf = new randomaccessfile ("F: // nepalon // rtest. dat", "RW ");
RF. Seek (5*8 );
RF. writedouble (47.0001 );
RF. Close ();
Rf = new randomaccessfile ("F: // nepalon // rtest. dat", "R ");
For (INT I = 0; I <10; I ++)
System. Out. println ("value" + I + ":" + RF. readdouble ());
RF. Close ();
}
}
Code explanation (in the unit of Zone ):
In Area 1, when reading a file, first read the file content to the cache, when calling in. readline (), and then read data from the cache in character format (hereinafter referred to as "cache byte read mode ").
In section 1B, to read data from the standard I/O (keyboard) as a cache byte, you must first set the standard I/O (system. in) is converted to a character-oriented stream and then encapsulated by bufferedreader.
In area 2, a stringreader stream is generated to read data from a string object in the form of characters.
In area 4, when reading data from String object S2, the data in the object is first stored in the cache and then read from the buffer; For testio. when operating the out file, the formatted Information is first output to the cache, and then the cached information is output to the file.
In Area 5, when outputting the data.txt file, the basic data type is first output to the House cache, and then the cached data is output to the file. when reading the file, first, read the data in the file to the cache, and then read the data in the basic type from the cache. Note the in5.readdouble () line. Because the first writedouble () is written, it must be correctly displayed. It also needs to be read in the form of basic types.
In Area 6, files are operated through the randomaccessfile class.
----
Important:
Linenumberinputstream and stringbufferinputstream have been abolished! Don't use it any more!
Stringbufferinputstream, this class does not properly convert characters into bytes!
Stringbufferinputstream, deprecated. This class incorrectly assumes that bytes adequately represent characters!
---------------- Caring about Io is the path to your future of Java! -----------------------
The entire Readline () method is not available in the datainputstream stream!
Replace with: bufferedreader d = new bufferedreader (New inputstreamreader (in ));
-------- Convert byte Transfer to the upstream stream access cache to read the upstream stream and then process it!
This method has great advantages!
----------------------
----------------- Why use character streams? ------------------
The primary advantage of character streams is that they make it easy to write programs that are not dependent upon a specific character encoding, and are therefore easy to internationalize.
Java stores strings in UNICODE, an international standard character encoding that is capable of representing most of the world's written ages. typical user-readable text files, however, use encodings that are not necessarily related to Unicode, or even to ASCII, and there are using such encodings. character streams hide the complexity of dealing with these encodings by providing two classes that serve as bridges between byte streams and character streams. the inputstreamreader class implements a character-input stream that reads bytes from a byte-input stream and converts them to characters according to a specified encoding. similarly, the outputstreamwriter class implements a character-output stream that converts characters into bytes according a specified encoding and writes them to a byte-output stream.
A second advantage of character streams is that they are potentially much more efficient than byte streams. the implementations of executions of Java's original byte streams are oriented around byte-at-a-time read and write operations. the character-stream classes, in contrast, are oriented around buffer-at-a-time read and write operations. this difference, in combination with a more efficient locking scheme, allows the character stream classes to make up for the added overhead of encoding conversion in seconds cases.
---------- Reading data from standard device system. In ------------------
-----------------------------------------------------
Read byte: bufferedinputstream
Read characters: bufferedreader + inputstreamreader
----------------------------------------------
Import java. Io .*;
Public class Systemin
{
Public static void main (string ARGs [])
{Try {// Stream Conversion!
Bufferedreader is = new bufferedreader (New inputstreamreader (system. In ))
String inputline = NULL;
While (inputline = is. Readline ())! = NULL)
System. Out. println (inputline );
Is. Close ();
}
Catch (ioexception E)
{System, out. println ("ioxe:" + E );
}
}
}
--------------------------------------------------------------------------------
----------------- The standard output system. Out is a print stream printstream ---------------------
Import java. Io .*;
Public class printstandardoutput {
Public static void main (string [] ARGs ){
String myanswer = "no, and that's final ,";
System. Out. println ("Hello world of Java ");
System. Out. println ("the answer is" + myanswer + "at this time .");
Printwriter PW = new printwriter (system. Out );
PW. println ("the answer is" + myanswer + "at this time .");
Int I = 42;
PW. println (I + '=' + "the answer .");
PW. println ("Note:" + I + '=' + "the answer .");
PW. println (I + "=" + "the answer .");
PW. println (I + ('=' + "the answer ."));
PW. Close ();
}
}
Bytes -----------------------------------------------------------------------------------
--------------------- To read (output to-) a text file -----------------------------
Bufferedreader is = new bufferedreader (New filereader ("XXXX. Text"); read
Bufferedoutputstream byteout = new bufferedoutputstream (New fileoutputstream ("XX. dat "));
// Write to text!
-----------------------------------------------
--------------- Use bufferedreader -- filereader to read text files! -----------
--------------- Always pay attention to the byte stream or the upstreaming stream -------------------- in Io ----------------------
-----------------------------------------------------------------------
Import java. Io .*;
Import java. AWT .*;
Import javax. Swing .*;
Import java. AWT. event .*;
Class filewindow extends jframe implements actionlistener
{
Jtextarea text;
Bufferedreader in;
Jbutton button;
Filereader file;
Filewindow ()
{
Super ("File Upload stream ");
Container con = getcontentpane ();
TEXT = new jtextarea (50, 50 );
Text. setbackground (color. Blue );
Try {
File F = new file ("E: // a.txt ");
File = new filereader (f );
In = new bufferedreader (File );
/** Bufferedreader (Reader in) constructor,
* Access bufferedreader to read stream filereader from file character
* Stream in order to use the bufferedreader object method Readline () to efficiently read rows!
*/
}
Catch (filenotfoundexception e ){}
Catch (ioexception e ){}
Button = new jbutton ("read ");
Button. addactionlistener (this );
Con. setlayout (New borderlayout ());
Setsize (300,200 );
Setvisible (true );
Con. Add (text, "center ");
Con. Add (button, "South ");
Addwindowlistener (New windowadapter ()
{Public void windowclosing (invalid wevent E)
{Setvisible (false); system. Exit (0 );}});
}
Public void actionreceivmed (actionevent E)
{
String S;
If (E. getsource () = button)
Try {
While (S = in. Readline ())! = NULL)
Text. append (S + '/N ');
// Here, you can also use bufferstring to temporarily Save the read character data!
}
Catch (ioexception E1 ){}
}
// --------- Main ()----------
Public static void main (string ARGs [])
{
Filewindow win = new filewindow ();
Win. Pack ();
}
}
----------------- Randomaccessfile randomly reads the file ---------------
Import java. Io .*;
Public class randomread
{
Final Static string filename = "E: // a.txt ";
Protected string filename;
Protected randomaccessfile seeker;
Public static void main (string [] argv) throws ioexception {
Randomread r = new randomread (filename );
System. Out. println ("offset is" + R. readoffset ());
System. Out. println ("message is/" "+ R. readmessage () + "/".");
}
/** Constructor: Save filename, construct randomaccessfile */
Public randomread (string fname) throws ioexception {
Filename = fname;
Seeker = new randomaccessfile (fname, "RW ");
}
/** Read the offset field, defined to be at location 0 in the file .*/
Public int readoffset () throws ioexception {
Seeker. Seek (0 );
Seeker. writechars (filename); // move to very beginning
Return Seeker. readint (); // and read the offset
}
/** Read the message at the given offset */
Public String readmessage () throws ioexception {
Seeker. Seek (120); // move to where
Return Seeker. Readline (); // and read the string
}
}
I did not want to talk about anything, but I still wrote it out in the spirit of being technically responsible.
I/O understanding is level 3 (if Java Io has level 10)
Too many errors.
Unfamiliar with I/O layers
Java Io mainly includes
Java. Io package and Java. Nio package.
Java. Io mainly extends from four interfaces:
Byte:
Inputstream/outputstream, Which is encapsulation, filtering, and specific implementation class for specific object processing.
Character:
Reader/writer (in the original article, all writer interfaces are written as write, which means you do not understand this interface at all. If you often use the writer interface, how can you tell the difference between writer and write, not a mistake, but all of them are write)
Among the above four interfaces, the underlying layer is all the blocked stream of Operation bytes.
Java. Nio is mainly based on block Operation blocks (buffer). Through the blocking and non-blocking modes that can be set, the data output is greatly improved.
It also controls the channel by selecting the selector mode, so that multiple users can concurrently transfer data in the same output input channel. for example, a socket port can be concurrently accessed by an infinite number of clients (theoretically unlimited. is the classic I/O multiplexing technology.