Examples of Bufferedinputstream and bufferedoutputstream use in Java _java

Source: Internet
Author: User
Tags flush int size

Bufferedinputstream
Bufferedinputstream is the buffered input stream. It inherits from FilterInputStream.
The role of Bufferedinputstream is to add functionality to another input stream, for example, to provide "buffering" and to support "mark ()" and "Reset () Reset methods."
The Bufferedinputstream is essentially implemented through an internal buffer array. For example, when a new input stream corresponds to a bufferedinputstream, and when we read the input stream's data through read (), Bufferedinputstream fills the input stream's data into the buffer in batches. Each time the data in the buffer is read, the input stream fills the data buffer again, and so on until we have finished reading the input stream data location.
Bufferedinputstream Function List:

Bufferedinputstream (InputStream in)
Bufferedinputstream (inputstream in, int size)

synchronized int   Available ()
void Close   ()
synchronized void   mark (int readlimit)
boolean   marksupported ()
synchronized int   read ()
synchronized int   read (byte[] buffer, int offset, int byteCount)
synchronized void   Reset ()
synchronized long   Skip (long ByteCount)

Sample code:
For detailed usage of APIs in Bufferedinputstream, refer to Sample code (Bufferedinputstreamtest.java):

Import Java.io.BufferedInputStream;
Import Java.io.ByteArrayInputStream;
Import Java.io.File;
Import Java.io.InputStream;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.io.FileNotFoundException;

Import java.lang.SecurityException; /** * Bufferedinputstream Test program * * @author Skywang/public class Bufferedinputstreamtest {private static final I

  NT LEN = 5;
  public static void Main (string[] args) {testbufferedinputstream (); /** * Bufferedinputstream API Test function/private static void Testbufferedinputstream () {//Create Bufferedinputs
      Tream byte stream, content is arrayletters array try {file = new file ("Bufferedinputstream.txt");

      InputStream in = new Bufferedinputstream (new FileInputStream (file), 512); Reads 5 bytes from a byte stream. "ABCDE", a corresponding 0x61,b corresponding to 0x62, and so on ... for (int i=0; i<len; i++) {//If you can continue to read the next byte, read the next byte if (In.availa BLE () >= 0) {//read "The next byte of the stream" int tmp = In.read();
        System.out.printf ("%d:0x%s\n", I, integer.tohexstring (TMP)); }///If "This byte stream" does not support the tagging feature, exit if (!in.marksupported ()) {System.out.println ("Make not supported!") directly
        );
      return;

      }//Mark "Current index position", the element that marks position 6th--"F"//1024 corresponds to Marklimit in.mark (1024);
      Skips 22 bytes.

      In.skip (22);
      Read 5 bytes byte[] buf = new Byte[len];
      In.read (buf, 0, LEN);
      Converts a buf to a string string.
      String str1 = new string (BUF);

      System.out.printf ("str1=%s\n", str1);
      Resets the input stream index to the position marked by Mark (), which is reset to "F".
      In.reset (); Reads 5 bytes into BUF from the reset byte stream.
      Read "Fghij" In.read (buf, 0, LEN);
      Converts a buf to a string string.
      String str2 = new string (BUF);

      System.out.printf ("str2=%s\n", str2);
    In.close ();
    catch (FileNotFoundException e) {e.printstacktrace ();
    catch (SecurityException e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace (); }
  }
}

 

The contents of the Bufferedinputstream.txt read in the program are as follows:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
abcdefghijklmnopqrstuvwxyz

Run Result:

0:0x61
1:0x62
2:0x63
3:0x64
4:0x65
str1=01234

Bufferedoutputstream
Bufferedoutputstream is the buffered output stream. It inherits from Filteroutputstream.
The role of Bufferedoutputstream is to provide a "buffering function" for another output stream.
Bufferedoutputstream Function List:

Bufferedoutputstream (OutputStream out)
Bufferedoutputstream (outputstream out, int size)

synchronized void Close   ()
synchronized void   flush ()
synchronized void   Write (byte[) buffer, int offset, int Length)
synchronized void   write (int onebyte)

Sample code:
For detailed usage of APIs in Bufferedoutputstream, refer to Sample code (Bufferedoutputstreamtest.java):

Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.OutputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.io.FileNotFoundException;
Import java.lang.SecurityException;

Import Java.util.Scanner;  /** * Bufferedoutputstream Test program * * @author Skywang/public class Bufferedoutputstreamtest {private static final
  int LEN = 5; corresponding to the English letter "abcddefghijklmnopqrsttuvwxyz" private static final byte[] Arrayletters = {0x61, 0x62, 0x63, 0x64, 0x65, 0  X66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,

  0X7A};
  public static void Main (string[] args) {testbufferedoutputstream (); /** * Bufferedoutputstream API Test function/private static void Testbufferedoutputstream () {//create "file output stream" corresponding BU
    Fferedoutputstream//Its corresponding buffer size is 16, that is, the buffer's data >=16, the contents of the buffer are automatically written to the output stream.
      try {File File = new file ("OUT.txt");
         OutputStream out =New Bufferedoutputstream (new FileOutputStream (file), 16);
      Writes the first 10 bytes of the arrayletters array to the output stream Out.write (arrayletters, 0, 10);

      Writes the newline character \ n to the output stream out.write (' \ n ');
      Todo!

      Out.flush ();

      Readuserinput ();
    Out.close ();
    catch (FileNotFoundException e) {e.printstacktrace ();
    catch (SecurityException e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace ();
    }/** * Read user input/private static void Readuserinput () {System.out.println ("Please input a text:");
    Scanner reader=new Scanner (system.in);
    Wait for an input String str = Reader.next ();
  System.out.printf ("The input is:%s\n", str);

 }
}

Run Result:
Generate file "OUT.txt", the contents of the file is "Abcdefghij".
Step-by-Step Testing: Test the program to see the buffer size and flush () in the following 3 steps, respectively.
The 1th kind: Original procedure
(1) running the program. When the program waits for user input, look at the textual content of "out.txt"; Discovery: Content is empty.
(2) running the program. After the user has entered, look at the textual content of "out.txt"; Discovery: Content is "Abcdefghij".
From this, we find that (01) and (02) the results are different; the OUT.txt content in (01) is empty because the out.txt corresponding buffer size is 16 bytes, and we write only 11 bytes, so it does not perform a flush buffer (that is, the buffered data is written to the output stream).
and (02) the content of the corresponding OUT.txt is "Abcdefghij" because the Out.close () is executed, it closes the output stream, and the data of the buffer is written to the output stream before the output stream is closed.
Note: When you re testing, remove the OUT.txt first.
2nd: Add the following statement before Readuserinput ()
Out.flush ();
The function of this sentence is to write "the contents of the buffer" into the output stream.
(1) running the program. When the program waits for user input, look at the textual content of "out.txt"; Discovery: Content is "Abcdefghij".
(2) running the program. After the user has entered, look at the textual content of "out.txt"; Discovery: Content is "Abcdefghij".
From this, we find (01) and (02) The same result, the corresponding OUT.txt content is "Abcdefghij". This is because the flush () operation is performed, which is to write the data of the buffer to the output stream.
Note: When you re testing, you first delete the out.txt!
The 3rd kind: On the basis of the 1th kind, will

Out.write (arrayletters, 0, 10);

Amended to

Out.write (arrayletters, 0, 20);

(1) running the program. When the program waits for user input, look at the textual content of "out.txt"; Discovery: Content is "Abcdefghijklmnopqrst" (not including carriage return).
(02) running the program. After the user has entered, look at the textual content of "out.txt"; Discovery: Content is "Abcdefghijklmnopqrst" (including carriage return).
From this we find that (01) The result of the operation is "Abcdefghijklmnopqrst" (without carriage return). This is because the size of the buffer is 16, and we have written 20 bytes through Out.write (arrayletters, 0, 20), which exceeds the size of the buffer, and the entire input is written directly into the output stream without passing through the buffer.
(3) The result of the run is "Abcdefghijklmnopqrst" (including carriage return), because the carriage return symbol ' \ n ' is written to the output stream when the Out.close () is executed.
Note: When you re testing, you first delete the out.txt!

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.