IO (iii) IO stream byte stream and bytes buffer flow (RPM)

Source: Internet
Author: User

In the I/O class library, Java.io.InputStream and java.io.OutputStream represent byte input streams and byte output streams, which are abstract classes that cannot be instantiated, and the smallest unit in the data flow is bytes, so it is called a byte stream.

The method of reading data in InputStream is as follows:

1, int read ()

Function: Reads a byte of data, and returns the read data, and if 1 is returned, it reads to the end of the input stream.

2, int read (byte[] b)

Function: Reads a certain amount of bytes from the input stream, stores it in byte array B, returns the number of bytes actually read, or returns 1, which indicates that the end of the input stream is read.

3, int read (byte[] b, int off, int len)

Function: Reads the data into a byte array, returns the actual number of bytes read, and returns 1 if it is read to the end of the input stream. OFF specifies the starting offset where the data is stored in array B, and Len specifies the maximum number of bytes to read.

4, available ()

Function: Returns the number of estimated bytes that a method call can read from or skip from this input stream without blocking.

5. Close ()

Function: Closes the input stream, releasing the associated resources for this stream.

Second, the method of writing data in OutputStream is as follows:

1, int write (int b)

Function: Writes the lowest byte of B to this input stream, and the other three bytes are discarded.

2, int write (byte[] b)

Function: Writes the specified byte array b to this input stream.

3, int write (byte[] b, int off, int len)

Function: Writes Len bytes from offset off to the input stream in the specified byte array.

4. Flush ()

Function: refreshes this input stream and forces the output bytes of all buffers to be written out.

5. Close ()

Function: Closes the output stream, releasing the associated resources for this stream.

① byte array input stream:

1 package com.iotest; 2  3 import java.io.ByteArrayInputStream; 4 import java.io.IOException; 5 public class Bytearryinputstreamdemo {6
   
    public static void Main (string[] args) throws IOException {7         String str = "Abcdefghijk"; 8         byte[] Strbuf = STR.G Etbytes ();  The string is converted into a byte array of 9         bytearrayinputstream Bais = new Bytearrayinputstream (STRBUF), and         int data = Bais.read ();          Reads bytes from byte array input stream one         while (data!=-1) {             upper = Character.touppercase (char) data);             System.out.print (upper+ "");             data = Bais.read ();         }16         bais.close ();     
   

Program Run Result: A B C D E F G H I J K

② byte array output stream:

1 package com.iotest; 2  3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5  6 public class Bytearrayoutputstreamdemo {7 public     static void Main (string[] args) throws IOException {8         Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); 9         String s = "Welcome to use Bytearrayoutputstreamdemo";         byte[] buf = S.getbytes ();         Baos.write (BUF);//writes the specified byte array to the byte array output stream,         System.out.println (baos.tostring ());  Converts the contents of a byte array output stream to a string output         //Copy the contents of the byte array output stream into a byte array         byte[] b = Baos.tobytearray (); N for         (int i = 0; I < b . length; i++) {             System.out.print (char) b[i]);         }18         baos.close ();     }20}

Program Run Result:
Welcome to use Bytearrayoutputstreamdemo
Welcome to use Bytearrayoutputstreamdemo

③ file input and output stream usage

 1 package com.iotest; 2 3 Import Java.io.File; 4 Import Java.io.FileInputStream; 5 Import java.io.FileNotFoundException; 6 Import Java.io.FileOutputStream; 7 Import java.io.IOException;         8//Copy Picture 9 public class Fileinputstreamdemo {Ten public static void Main (string[] args) throws IOException {11 File File = new file ("F:\\shar\\test\\logo17.gif"); FileInputStream fis = new FileInputStream (file); Create an input stream 13//create an output stream, followed by a parameter true to append, the original content is not cleared, the default is false14 fileoutputstream fos = new FileOutputStream ("F:\             \shar\\test\\logo18.gif ", false); int ch = 0;16//Way 117/*while ((Ch=fis.read ())! =-1) {18 Fos.write (CH); 19}*/20//mode 221/*byte[] b = new byte[1024];22 while ((Ch=fis.read (b))         ! =-1) {fos.write (b,0,ch); 24}*/25//Way 326 byte[] B = new byte[fis.available ()];27 Fis.read (b);  First read the contents of the FIS to byte array b inside Fos.write (b);//The contents of byte array B are then written to the specified file by the output stream 29       Closed stream Fos.close (); Fis.close (); 32}33 34} 

④ use of pipeline flow:
A PipedInputStream object must be connected to a PipedOutputStream object to produce a communication pipeline. Typically one thread writes data from the pipeline output stream, and the other thread reads the data from the pipeline input stream. When thread a executes the read () method of the pipeline input stream, if no data is temporarily available, the thread will be blocked and thread A will resume running only if thread B wants to write the data to the pipeline output streams.

Package Com.iotest;import Java.io.ioexception;import Java.io.pipedinputstream;import java.io.pipedoutputstream;/* *    Pipe Flow */class Sender extends thread{private pipedoutputstream out = new PipedOutputStream ();    Public PipedOutputStream Getout () {return out;        } @Override public void Run () {String s = ' Hello World ';            try {out.write (s.getbytes ());        Out.close (); } catch (Exception e) {//Todo:handle Exception}}}public class Receiver extends thread{privat    e PipedInputStream in;    Public Receiver (sender) throws IOException {in = new PipedInputStream (Sender.getout ());            } @Override public void Run () {try {int data;            while ((Data=in.read ())!=-1) {System.out.print ((char) data);        } in.close (); } catch (Exception e) {//Todo:handle Exception}} public static void Main (string[] args) throw S IOException {Sender sender = new sender ();        Receiver R = new Receiver (sender);        Sender.start ();    R.start (); }}

⑤ use of buffered streams:

 1 package com.iotest; 2 3 Import Java.io.BufferedInputStream; 4 Import Java.io.BufferedOutputStream; 5 Import Java.io.FileInputStream; 6 Import java.io.FileNotFoundException; 7 Import Java.io.FileOutputStream; 8 Import java.io.IOException; 9 public class Testprime {One private Bufferedinputstream bis = null;12 private bufferedoutputstream bos = NULL; String fileName = "F:\\shar\\test\\test2.txt", and the static int s,p;15//Determines whether a prime number is a public boolean isprime (i          NT N) {(int i=2;i<=n/2;i++) {n%i = = 0) {return false;20}21         }22 return true;23}24 void printprime (int m) throws ioexception{25//byte flow buffer stream 26 BOS = new Bufferedoutputstream (new FileOutputStream (fileName)), int j = 0;28 for (int i = 2; i < m; I + +) {if (IsPrime (i)) {j++;31 if (j%s = = 0) {+-String s = String.valueof (i) + ""; 33                     Bos.write (S.getbytes ()); Bos.write ("\ r \ n". GetBytes ());}else{                 A String s = string.valueof (i) + ""; PNs Bos.write (S.getbytes ()); 38 }39}40}41 Bos.flush (); Bos.close ();}44 void Getprime () throws Ioexcepti on{45//byte flow buffer stream: bis = new Bufferedinputstream (new FileInputStream (fileName)); int c = Bis.rea D (); and (c! =-1) {c;50-char ch = (char) System.out.print (ch); n = bis. Read ();}53}54/**55 * @param args56 * @throws IOException, */58 public static Voi          D main (string[] args) throws IOException {Testprime t = new Testprime (); p = 100;61 s = 10;62 T.printprime (P); T.getprime (); 64}65 66}

If the stream is not buffered, the program reads a data and writes a data. This greatly affects the efficiency in a program with large data volumes. The buffer stream function is to write the data to the buffer, wait for the buffer full, and then write the data into the file. So the efficiency is greatly improved.
Original address: http://www.cnblogs.com/liuling/archive/2013/05/07/InputStreamAndOutputStream.html

IO (iii) IO stream byte stream and bytes buffer flow (RPM)

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.