Input and output--io streams

Source: Internet
Author: User

    • Javaio Flow
The first thing to understand is this stream word: Java abstracts different inputs, output sources into streams, and allows Java programs to use the same way to access different inputs and output sources through streaming. It would be nice to simply interpret the "flow" here as an ordered data from origin to acceptance.
    • Classification of IO streams:
There are 3 ways of classifying:

1, according to the direction of flow:

input stream; output stream

2, according to the processing unit:

BYTE stream (8-bit bytes); character Stream (16-bit bytes)

3, by the role of the stream:

Node stream: A stream that can read/write data from a specific IO device

Process flow: Connects and encapsulates an existing stream and implements the data read/write operation through the encapsulated stream.


Java's IO stream involves more than 40 classes, though much, but don't panic, he has rules. Remember that 3 o'clock is good:
1, all classes are derived from 4 abstract classes. These 4 abstract classes are: InputStream & Reader;outputstream & Writer.
2, input and output no difference, but one is to read, one is to write. There is no difference between a byte stream and a character stream, except that the data cells they manipulate are different: one is bytes and one is a character. Generally speaking: if the content that needs to input and output is text content, consider using character stream, if the content that needs to input and output is binary content, this time use byte stream.
3, using Advanced streaming:
1), convert stream: Converts byte streams to character stream (Inputstreamreader,outputstreamwriter).

2), processing flow: uses the processing flow to wrap the node stream, and the program executes the input and output by processing the stream. Recognizing the processing flow is also very simple: as long as the constructor parameter of the stream is not a physical node, but an already existing stream, then this flow is the process flow. Here's a more common use of processing streams: Java uses system.in to represent standard input, which is keyboard input, but this standard input stream is an instance of the InputStream class, it is not very convenient to use, and we know that the keyboard input content is text content, so we can use the inputs Treamreader convert it into a character input stream, ordinary reader reading input is not very convenient, we can wrap reader into Bufferreader, using Bufferreader ReadLine method can read a line of content at one time.


The following pieces of code are used to illustrate several commonly used streams:

Import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.ioexception;public class Linkin{ public static void Main (string[] args) throws ioexception{fileinputstream fis = null; FileOutputStream fos = null;try{//Create byte input stream fis = new FileInputStream ("Src/linkin.java");//create byte output stream fos = new Fileoutputstre AM ("Src/newfile.java"); byte[] Bbuf = new Byte[32];int Hasread = 0;//loop extracts data from the input stream while (Hasread = Fis.read (bbuf)) > 0) { Every read, that is, write the file output stream, read how much, just write how much. Fos.write (bbuf, 0, Hasread);}} catch (IOException IoE) {ioe.printstacktrace ();} Finally{if (FIS! = null) {Fis.close ();} if (fos! = null) {Fos.close ();}}}}

Import Java.io.filereader;import Java.io.filewriter;import java.io.ioexception;public class Linkin{public static void Main (string[] args) throws ioexception{filereader fr = null; FileWriter FW = null;try{//Create character input stream fr = new FileReader ("Src/linkin.java");//Create a "bamboo tube" of length 32 char[] Cbuf = new char[32];//with To save the number of characters actually read int hasread = 0;//use a loop to repeat the "fetch" process while ((Hasread = Fr.read (cbuf)) > 0) {//Remove the "bamboo" in the water droplets (characters), convert the character array into string input! System.out.print (New String (cbuf, 0, Hasread));} FW = new FileWriter ("Poem.txt"); Fw.write ("Jin-li shangyin \ r \ n"); Fw.write ("The brocade is unprovoked 50 chord, one string one pillar thinks Chinese year." \ r \ n "); Fw.write (" Butterfly Dream fan Butterfly, Wang hath-tai cuckoo. " \ r \ n "); Fw.write (" The Pearl of the Sea Moon has tears, Lantian day warm jade smoke. " \ r \ n "); Fw.write (" The feeling can be recalled, but it was already disconsolate. ") \ r \ n ");} catch (IOException IoE) {ioe.printstacktrace ();} Finally{if (fr! = null) {Fr.close ();} if (fw! = null) {Fw.close ();}}}}

Import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.printstream;public class Linkin{public static void Main (string[] args) throws ioexception{fileoutputstream fos = null; PrintStream PS = Null;try{fos = new FileOutputStream ("Test.txt");p s = new PrintStream (FOS);// Use PrintStream to perform output ps.println ("normal string"), or//direct use of PrintStream output Object Ps.println (new Linkin ());} catch (IOException IoE) {ioe.printstacktrace ();} FINALLY{IF (PS! = null) {Ps.close ();}}}}

Import Java.io.ioexception;import Java.io.stringreader;import Java.io.stringwriter;public class Linkin{public static void Main (string[] args) throws Ioexception{stringreader sr = null; StringWriter SW = null; String src = "From tomorrow, be a happy person \" + "Feed the horse, chop wood, travel around the world \" + "From tomorrow, care for food and vegetables \" + "I have a house, facing the sea, spring flowers \" + "from tomorrow, and every family communication \ n" + "tell them my happiness \ n "; char[] buffer = new Char[32];int Hasread = 0;TRY{SR = new StringReader (src);//Read the string with a loop read access while (Hasread = Sr.read (b Uffer)) > 0) {System.out.print (new String (buffer, 0, hasread));}} catch (IOException IoE) {ioe.printstacktrace ();} try{//when creating StringWriter, actually a stringbuffer as the output node//below the specified 20 is the initial length of the stringbuffer SW = new StringWriter ();// Call StringWriter's method to execute the output sw.write ("There is a beautiful new world, \ n"); Sw.write ("She waits for me in the distance, \ \"); Sw.write ("Where there is naïve child, \ n"); Sw.write ("and the dimples of the girl. n "); SYSTEM.OUT.PRINTLN ("----below is the contents of the SW string node----");//Use the ToString () method to return the contents of the string node of StringWriter System.out.println ( Sw.tostring ());} catch (Exception IoE) {ioe.printstacktrace ();} Finally{if (SR! = NULL) {Sr.close ();} if (sw! = null) {Sw.close ();}}} 


Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;public class Linkin{ public static void Main (string[] args) throws ioexception{inputstreamreader reader = null; BufferedReader br = null;try{//converts sytem.in objects into reader object reader = new InputStreamReader (system.in);// The general reader is packaged as BUFFEREDREADERBR = new BufferedReader (reader); String buffer = null;//takes a circular way to read a row of while (buffer = Br.readline ()) = null) {//If the read string is ' exit ', the program exits if (Buffer.equals (" Exit ") {System.exit (1);} Print Read content System.out.println ("Input:" + buffer);}} catch (Exception IoE) {ioe.printstacktrace ();} Finally{if (BR! = null) {Br.close ();}}}}


For some of the above code, there are a few things to note:
1, in the use of low-level flow often will be new a 1024 byte array, which is equivalent to a bamboo tube to operate the flow, the pointer to the corresponding jump back.
2. After using the IO stream, remember to close the stream. Garbage collection cannot be reclaimed because the program opens a file IO resource that is not part of the in-memory resource. By using IO Stream execution to close the stream, not only can the stream's physical resource be recycled, but the output stream cache data can also be flush to the physical node. After we have used the processing flow to wrap the underlying stream, we just need to close the topmost stream, and the lower stream below will be automatically closed.
The input function of the 3,printstream class is very powerful, usually if we need to output text content, the output stream should be packaged into printstream after the output.


Input and output--io streams

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.