Java input/output stream (2)

Source: Internet
Author: User

Java input/output stream (2)

6. Java. IO stream class library

1. Four Basic classes of io streams

The java. io package contains all classes required for stream I/O. There are four basic classes in the java. io package: InputStream, OutputStream, Reader, and Writer. They process byte streams and response streams respectively:

Basic data flow I/O

Input/Output

Byte stream

Ghost stream

Input stream

Inputstream

Reader

Output stream

OutputStream

Writer


In Java, other diverse stream types are derived from them:

JDK1.4 introduced the new I/O class library, which is located in the java. nio package. The new I/O class library uses channels and buffers to improve the efficiency of I/O operations.

In the java. io package, java. io. InputStream indicates the byte input stream, and java. io. OutputStream indicates the byte output stream, which is at the top of the java. io package. These two classes are abstract classes, that is, they cannot be instantiated. They must be generated before certain functions can be implemented.

1. Specific categories of io streams

I. Overall classification by I/O type:

1. Memory <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization/P8sTatObK/authorization/yxNq05tfWt/u0rrbB0LTK/authorization + signature/Signature + oaO21M7EvP69 + signature/Signature + 3crHSmF2YbXEu/Signature + signature + Signature release/LQtLP2yrGjrLbUyv2 + release/release + IM2ouf27urTmu/release + release/qGisLTK/release + release/release + CjxwPgo8L3A + cgo8aDI + CjxwIGNsYXNzPQ = "headline-1 bk-sidecatalog-title"> 7. byte stream InputStream/OutputStream

1. InputStreamAbstract class

InputStream is a byte input stream. It is an abstract class and must rely on its subclass to implement various functions. This abstract class is a superclass that represents all classes of the byte input stream. Streams inherited from InputStream are all input data to the program, and the data unit is 8 bits );

InputStream is a class used to input byte data. Therefore, the InputStream class provides three overloaded read methods. Common methods in the Inputstream class:
(1) public abstract int read (): reads data of a byte. The returned value is an int type value with a high value of 0. If the returned value is-1, it indicates that no Bytes are read.
(2) public int read (byte B []): read data in byte B. length and put it in array B. The returned value is the number of bytes read. This method is actually implemented by calling the next method.
(3) public int read (byte B [], int off, int len): reads data of up to len bytes from the input stream and stores the data in the B array with the offset of off.
(4) public int available (): returns the number of bytes that can be read from the input stream. Note: If the input is blocked, the current thread will be suspended. If the InputStream object calls this method, it will only return 0. This method must be called by a subclass object that inherits the InputStream class,
(5) public long skip (long n): Ignore n bytes in the input stream. The returned value is the number of bytes actually ignored. skip some bytes to read
(6) public int close (): we must close the opened stream after use.

Main subclass:

1) FileInputStream uses a file as InputStream to read the file.
2) ByteArrayInputStream: uses a buffer in the memory as an InputStream.
3) StringBufferInputStream: Use a String object as InputStream.
4) PipedInputStream: implements the pipe concept and is mainly used in the process.
5) SequenceInputStream: combines multiple inputstreams into one InputStream.

2. OutputStreamAbstract class OutputStream provides three write methods for data output, which corresponds to InputStream.
1. public void write (byte B []): write the bytes in parameter B to the output stream.
2. public void write (byte B [], int off, int len): write the len bytes of parameter B starting from offset off to the output stream.
3. public abstract void write (int B): first converts int to byte type and writes low bytes to the output stream.
4. public void flush (): outputs all data in the data buffer and clears the buffer.
5. public void close (): close the output stream and release the system resources related to the stream.

Main subclass:

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.

Stream end judgment: when the return value of the read () method is-1, when the return value of readLine () is null.

3. file input stream: FileInputStream class

FileInputStream can use the read () method to read one byte at a time and return it as an int type, or read it into a byte array using the read () method. The number of elements in the byte array, the number of bytes read. In the process of reading or writing the entire file, such a byte array is usually treated as a buffer, because such a byte array usually plays an intermediate role to undertake data.


Function: data stream that uses files as the data input source. Or a class that opens a file and reads data from the file to the memory.
Usage (1)
File fin = new File ("d:/abc.txt ");
FileInputStream in = new FileInputStream (fin );

Usage (2)
FileInputStream in = new FileInputStream ("d:/abc.txt ");

Program example:
Display the content of the InputFromFile. java program on the monitor.


  1. Import java. io. IOException;
  2. Import java. io. FileInputStream;
  3. ;
  4. Public class TestFile {
  5. Public static void main (String args []) throws IOException {
  6. Try {
  7. FileInputStream rf = new FileInputStream ("InputFromFile. java ");
  8. Int n = 512; byte buffer [] = new byte [n];
  9. While (rf. read (buffer, 0, n )! =-1) & (n> 0 )){
  10. System. out. println (new String (buffer ));
  11. }
  12. System. out. println ();
  13. Rf. close ();
  14. } Catch (IOException IOe ){
  15. System. out. println (IOe. toString ());
  16. }
  17. }
  18. }

    4.File output stream: FileOutputStream classFunction: it is used to process data streams that use files as data outputs, or read data from the memory.

    The FileOutputStream class is used to process data streams that output files. A string that represents a File name can also be a File or FileDescriptor object.
    There are two methods to create a file stream object:
    Method 1:
    File f = new File ("d:/myjava/write.txt ");
    FileOutputStream out = new FileOutputStream (f );
    Method 2:
    FileOutputStream out = new FileOutputStream ("d:/myjava/write.txt ");
    Method 3: The constructor uses the FileDescriptor () object as its parameter.
    FileDescriptor () fd = new FileDescriptor ();
    FileOutputStream f2 = new FileOutputStream (fd );
    Method 4: The constructor uses the file name as its first parameter and the Boolean value as the second parameter.
    FileOutputStream f = new FileOutputStream ("d:/abc.txt", true );
    Note: (1) when writing data in a file, if the file already exists, it overwrites the existing file; (2) when the read/write operation ends, the close method should be called to close the stream.

    Program example: Use a keyboard to input the documents and save the documents to the write.txt file.
    1. Import java. io. IOException;
    2. Import java. io. FileOutputStream;
    3. Public class TestFile {
    4. Public static void main (String args []) throws IOException {
    5. Try {
    6. System. out. println ("please Input from Keyboard ");
    7. Int count, n = 512;
    8. Byte buffer [] = new byte [n];
    9. Count = System. in. read (buffer );
    10. FileOutputStream wf = new FileOutputStream ("d:/myjava/write.txt ");
    11. Wf. write (buffer, 0, count );
    12. Wf. close (); // when the stream write operation ends, call the close method to close the stream.
    13. System. out. println ("Save to the write.txt ");
    14. } Catch (IOException IOe ){
    15. System. out. println ("File Write Error! ");
    16. }
    17. }
    18. } 5. The fileinputstreamstream and fileoutputstreamapp use the file1.txt file to file2.txt.
      1. Import java. io. File;
      2. Import java. io. IOException;
      3. Import java. io. FileOutputStream;
      4. Import java. io. FileInputStream;
      5. Public class TestFile {
      6. Public static void main (String args []) throws IOException {
      7. Try {
      8. File inFile = new File ("copy. java ");
      9. File outFile = new File ("copy2.java ");
      10. FileInputStream finS = new FileInputStream (inFile );
      11. FileOutputStream foutS = new FileOutputStream (outFile );
      12. Int c;
      13. While (c = finS. read ())! =-1 ){
      14. FoutS. write (c );
      15. }
      16. FinS. close ();
      17. FoutS. close ();
      18. } Catch (IOException e ){
      19. System. err. println ("FileStreamsTest:" + e );
      20. }
      21. }
      22. }
        6. buffer the input/output stream BufferedInputStream/BufferedOutputStream

        It takes a lot of time for a computer to access external devices. The higher the Access frequency, the higher the probability of idle CPU. To reduce the number of external memory accesses, you should read and write more data in one access to the peripherals. To this end, in addition to the read/write mechanism required for data exchange between programs and stream nodes, a buffer mechanism should also be added. A buffer stream allocates a buffer for each data stream, and a buffer zone is the memory for temporary data storage. This can reduce the number of visits to the hard disk and improve the transmission efficiency.

        BufferedInputStream: When writing data to the buffer stream, the data is first written to the buffer zone. After the buffer zone is full, the system sends the data to the output device at one time.

        BufferedOutputStream: when reading data from the buffer stream, the system first reads data from the buffer zone. When the buffer zone is empty, the system then reads data from the input device to the buffer zone.

        1) read files into memory:

        Connect BufferedInputStream with FileInputStream

        FileInputStream in = new FileInputStream (optional file1.txt ");

        BufferedInputStream bin = new BufferedInputStream (in );

        2) write the memory into the file:

        Connect BufferedOutputStream with FileOutputStream

        FileOutputStreamout = new fileoutputstream(file1.txt ");

        BufferedOutputStream bin = new BufferedInputStream (out );


        3) read the keyboard input stream to the memoryConnect BufferedReader with standard data streams InputStreamReader sin = new InputStreamReader (System. in); BufferedReader bin = new BufferedReader (sin );
        1. Import java. io .*;
        2. Public class ReadWriteToFile {
        3. Public static void main (String args []) throws IOException {
        4. InputStreamReader sin = new InputStreamReader (System. in );
        5. BufferedReader bin = new BufferedReader (sin );
        6. FileWriter out = new FileWriter ("myfile.txt ");
        7. BufferedWriter bout = new BufferedWriter (out );
        8. String s;
        9. While (s = bin. readLine (). length ()> 0 ){
        10. Bout. write (s, 0, s. length ());
        11. }
        12. }
        13. } Program description:
          The method for reading characters from the keyboard and writing them into the file BufferedReader class: String readLine ()
          Purpose: Read a string and end with a carriage return.
          BufferedWriter class method: bout. write (String s, offset, len)
          Purpose: Write string s from offset and len Length to somewhere in the buffer zone.

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.