Read-write operations for the most complete Java (reprint)

Source: Internet
Author: User

The input and output streams in the Java I/O system provide a lot of convenience for us to develop, leveraging its strong encapsulation capabilities, which can be implemented in a variety of combinations. But Java provides a lot of input and output stream classes, in terms of concept and use a lot of similarities, so many developers have trouble, when should use what kind of input and output stream class become a problem.

The following is an introduction to the Java input and output stream class, accompanied by an example description of the use of each class has a brief analysis.

Introduction to the input and output stream classes

1.stream represents any data source capable of producing data, or any receiving source capable of receiving data. In Java IO, all streams (both input and out stream) include two types: byte-oriented stream and Unicode character-oriented stream.

1.1 Byte-oriented stream

A byte-oriented stream that represents reading from the stream in bytes or writing information to the stream. The byte-oriented stream includes the following types:

Input stream:

1) Bytearrayinputstream: Use a buffer in memory as a InputStream
2) StringBufferInputStream: Use a String object as a InputStream
3) FileInputStream: To use a file as a inputstream, to achieve the read operation of the file
4) PipedInputStream: realized the concept of pipe, mainly used in the thread
5) Sequenceinputstream: Merge multiple inputstream into one InputStream

Out stream:

1) Bytearrayoutputstream: Storing information in a buffer in memory
2) FileOutputStream: Depositing information into a file
3) PipedOutputStream: realized the concept of pipe, mainly used in the thread
4) Sequenceoutputstream: Merge multiple outstream into one OutStream

1.2 Unicode character-oriented stream

A Unicode-oriented stream that represents a Unicode character that reads from or writes information to a stream. The Unicode character-oriented stream includes the following types:

Input Stream:

1) CharArrayReader: corresponds to Bytearrayinputstream
2) StringReader: corresponds to StringBufferInputStream
3) FileReader: corresponds to FileInputStream
4) Pipedreader: corresponds to PipedInputStream

Out Stream:

1) Chararraywrite: corresponds to Bytearrayoutputstream
2) Stringwrite: No corresponding byte-oriented stream
3) FileWrite: corresponds to FileOutputStream
4) Pipedwrite: corresponds to PipedOutputStream

The character-oriented stream basically has a byte-oriented stream corresponding to it. Two corresponding classes implement the same function, the word is in the direction of the operation is different. such as CharArrayReader: and Bytearrayinputstream's role is to use a buffer in memory as InputStream, the difference is that each time a byte from memory read information, the latter each time from memory read a character.

1.3 Conversion between two non-current-directed streams

InputStreamReader and Outputstreamreader: Converts a byte-oriented stream into a character-oriented stream.

2. Adding a property to a stream

2.1 Function of "add attribute to stream"

Using the API of operation IO in Java described above, we can do whatever we want to do. But with subclasses of FilterInputStream and Filteroutstream, we can add properties to the stream. Here is an example of how this function works. If we are going to write data to a file, we can do this:

Fileoutstream fs = new Fileoutstream ("test.txt");

The write () function can then be called by the resulting FS object to the data in the Test.txt file. However, if we want to implement the "first to write the data to the file into memory, and then write the cached data into the file" function, the above API will not be able to meet our needs. But with FilterInputStream and Filteroutstream subclasses, add the functionality we need for fileoutstream.

Various types of 2.2 FilterInputStream

The 2.2.1 is used to encapsulate byte-oriented InputStream

1) DataInputStream: reads the base type (int, char, etc.) data from the stream.
2) Bufferedinputstream: Using buffers
3) Linenumberinputstream: The number of rows in the input stream is recorded and can then be called Getlinenumber () and setlinenumber (int)
4) Pushbackinputstream: Rarely used, generally used for compiler development

The 2.2.2 is used to encapsulate character-oriented InputStream

1) There is no class corresponding to the DataInputStream. Use DataInputStream unless you want to use ReadLine () instead of BufferedReader
2) BufferedReader: corresponds to Bufferedinputstream
3) LineNumberReader: corresponds to Linenumberinputstream
4) Pushbackreader: corresponds to Pushbackinputstream

Various types of 2.3 filteroutstream

The 2.2.3 is used to encapsulate byte-oriented outputstream

1) DataOutputStream: Outputs the basic type (int, char, etc.) data to stream.
2) Bufferedoutstream: Using buffers
3) PrintStream: produces formatted output

The 2.2.4 is used to encapsulate character-oriented OutputStream

1) Bufferedwrite: corresponds to Bufferedoutstream
2) Printwrite: corresponds to PrintStream

3. Randomaccessfile

1) Read and write files can be completed by Randomaccessfile object
2) When generating an object, you can indicate the nature of the file to be opened: R, read only, W, write only, rw readable and writable
3) You can jump directly to the location specified in the file

input and output stream application example

Here are 6 code snippets in the main function that illustrate how each input and output stream class is used, followed by a corresponding comment after the code snippet.

Java code
ImportJava.io.*;  Public   classtestio{ Public   Static   voidMain (string[] args)throwsioexception{//1. Read data from a file in a behavior unitBufferedReader in =NewBufferedReader (NewFileReader ("F:\\nepalon\\testio.java")); String s, S2=NewString ();  while((s = in.readline ())! =NULL) S2+ = s + "\ n";    In.close (); //When the file is read, the contents of the file are read into the cache, and when In.readline () is called, the data is read from the cache as a character ("cache bytes read"). //1b. Receiving keyboard inputBufferedReader stdin =NewBufferedReader (NewInputStreamReader (system.in)); System.out.println ("Enter a line:");    System.out.println (Stdin.readline ()); //because you want to read data from a standard IO (keyboard) in cache byte reads, you first convert the standard IO (system.in) to a character-directed stream and then the BufferedReader package. //2. Reading data from a string objectStringReader in2 =NewStringReader (S2); intC;  while((c = In2.read ())! = 1) System.out.println (Char) c);    In2.close (); //To read data from a string object in the form of a character, a stream of type StringReader is generated. //3. Remove the formatted input from the memoryTry{datainputstream in3=NewDataInputStream (NewBytearrayinputstream (S2.getbytes ()));  while(true) System.out.println (Char) In3.readbyte ()); }    Catch(eofexception e) {System.out.println ("End of Stream"); }      //4. Output to FileTry{BufferedReader in4=NewBufferedReader (NewStringReader (S2)); PrintWriter OUT1=NewPrintWriter (NewBufferedWriter (NewFileWriter ("f:\\nepalon\\ testio.out"))); intLineCount = 1;  while((s = in4.readline ())! =NULL) out1.println (LineCount+ + + ":" +s);    Out1.close ();    In4.close (); }    Catch(Eofexception ex) {System.out.println ("End of Stream"); }    //when the data is read by the string Object s2, the data in the object is stored in the cache and then read from the buffer, and when the Testio.out file is manipulated, the formatted information is output to the cache and the information in the cache is output to the file. //5. Storage and recovery of dataTry{DataOutputStream Out2=NewDataOutputStream (NewBufferedoutputstream (NewFileOutputStream ("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=NewDataInputStream (NewBufferedinputstream (NewFileInputStream ("f:\\nepalon\\ Data.txt"))); BufferedReader in5br=NewBufferedReader (NewInputStreamReader (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"); }    //the output of the Data.txt file is to output the basic type of data in the house cache, and then output the data in the cache to a file; When the file is read, the data in the file is read into the cache and then read from the cache in the form of a basic type. Note the in5.readdouble () line. Because the first writedouble () is written, it is intended to be displayed correctly.      It should also be read in the form of a basic type. //6. Working with Randomaccessfile filesRandomaccessfile RF =NewRandomaccessfile ("f:\\nepalon\\ rtest.dat", "RW");  for(inti=0;   I <10; i++) rf.writedouble (i*1.414);      Rf.close (); RF=NewRandomaccessfile ("f:\\nepalon\\ rtest.dat", "R");  for(inti=0;   I <10; i++) System.out.println ("Value" + i + ":" +rf.readdouble ());      Rf.close (); RF=NewRandomaccessfile ("f:\\nepalon\\ rtest.dat", "RW"); Rf.seek (5*8); Rf.writedouble (47.0001);      Rf.close (); RF=NewRandomaccessfile ("f:\\nepalon\\ rtest.dat", "R");  for(inti=0;   I <10; i++) System.out.println ("Value" + i + ":" +rf.readdouble ());    Rf.close (); }    }   

Read the above explanation, is not the Java input and output stream class concept has a clearer understanding of their use is also more handy?

Read-write operations for the most complete Java (reprint)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.