Turn Java input and output stream details (very detailed)

Source: Internet
Author: User

Turn http://blog.csdn.net/zsw12013/article/details/6534619

Provides system input and output through data flow, serialization, and file systems .

Java abstracts data from these disparate sources and targets into data streams. The Java language input and output function is very powerful and flexible, the drawback is that the code that looks like the input and output is not very concise, because you often need to wrap many different objects.

In the Java class Library, the IO part of the content is very large, because it involves a wide range of fields: standard input and output, file operation, data flow on the network, string stream, object flow, zip file stream .

1.1. Classification of Java streams by flow direction: input Stream: Programs can reading DataThe stream.
output Stream: The program can Write DataThe stream. By unit of data transfer: Byte stream: To byte unitsStream of data transferred
character Stream: To the character is the unitThe stream of transmitted data is divided by function: Node Stream: For direct manipulation of the target device's flow
Filter Flow: Yes to an existing links and encapsulation of streams, it provides powerful and flexible reading and writing function for the program by processing the data. 1.2, Java.io Common class

All stream classes provided by the JDK are located in the Java.io package, each inheriting from the following four abstract stream classes:

InputStream: Streams that inherit from InputStream are used to input Data, and the data units are bytes(8-bit).
Outputsteam: Streams that inherit from OutputStream are programs that are used to outward Output Data, and the data units are bytes(8-bit).
Reader:Streams that inherit from reader are used in the program input Data, and the data The units are all characters(16-bit).
Writer: Streams that inherit from writer are programs that are used to outward Output Data, and the data The units are all characters(16-bit).

The Java language input and output function is very powerful and flexible, the drawback is that the code that looks like the input and output is not very concise, because you often need to wrap many different objects. In the Java class Library, the IO portion of the content is very large, because it involves a wide range of fields: standard input and output, file operation, data flow on the network, string stream, object flow, zip file stream .... The purpose of this article is to give you a brief introduction.

Flow is a very image concept, when the program needs to read the data , it will open a stream to the data source , the data source can be a file, memory, or network connection. Similarly, when a program needs to write data , it opens a stream to the destination . At this point you can imagine that the data is like "flow" in this, such as:

There are two types of streams in Java, one is a byte stream, the other is a character stream, represented by four abstract classes (each stream consists of two inputs and outputs, so altogether four):Inputstream,outputstream,reader,writer . Other varied streams in Java are derived from them:(You cannot create an instance directly, you must create an instance with a subclass)

Stream represents any data source that is capable of producing data, or any receiving source that is capable of receiving data. In Java IO, all streams (including InputStream and out stream) include two types:

(1) Byte stream

Represents reading from a stream in bytes or writing information to a stream, which is a derived class of the InputStream class and the OutputStream class in the IO package . Usually used to read binary data, like and sound .

(2) Character stream

A Unicode-oriented stream that represents a Unicode character that reads from or writes information to a stream.

Difference:

  The main problem that reader and writer have to solve is internationalization . The original I/O class library only supports 8-bit byte streams, so it is not possible to handle 16-bit Unicode character streams well. Unicode is an internationalized character set (not to mention that Java's built-in char is a 16-bit Unicode character), so that after reader and writer are added, all I/O supports Unicode . In addition, the new class library has better performance than the old ones.

However, read and write are not replacements for InputStream and OutputStream, and sometimes you must also use byte-based classes and character-based classes. For this purpose, it also provides two "adapter (adapter)" classes. InputStreamReader is responsible for converting inputstream into reader, while OutputStreamWriter converts outputstream into writer.

A Hierarchy of flows

Defined:

(1) Java reads the data object into the input stream, and the object to which it is written is called the output stream. The structure diagram is as follows:

Input stream

Output stream

Two InputStream class

 both the InputStream class and the OutputStream class are abstract classes and cannot create objects that can be instantiated by subclasses .

InputStream is a class for inputting byte data, so the InputStream class provides 3 overloaded read methods . Common methods in the InputStream class:

(1) Public abstract int read (): Reads a byte of data, and the return value is the int type value of the high 0.

(2) public int read(byte b[]): reads b.length bytes of data into a B array. The return value is the number of bytes read. The method is actually called by the next method to implement the

(3) public int read(byte b[], int off, int len): reads up to len bytes of data from the input stream and stores it in a B array with an offset of off.

(4) public int available (): Returns the number of bytes that can be read in the input stream. Note: If the input is blocked, the current thread will be suspended, and if the InputStream object calls this method, it will only return 0, and the method must be called by the subclass object that inherits the InputStream class.

(5) Public long Skip (long N): ignores n bytes in the input stream, the return value is the number of bytes actually ignored, skips some bytes to read

(6) public int Close (): We must close our open stream after we have finished using it.

Three OutputStream class

  OutputStream provides 3 write methods to do the output of the data , which is relative to InputStream.

1. public void Write (byte b[]): Writes the bytes in parameter B to the output stream.

2. public void Write (byte b[], int off, int len) : Writes Len bytes from the offset off of parameter B to the output stream.

3. Public abstract void write (int b) : Converts an int to a byte type and writes low bytes to the output stream.

4. public void Flush (): Outputs all data in the data buffer and empties the buffer.

5. public void Close (): closes the output stream and frees the system resources associated with the stream.

Attention:

1. The above methods are likely to cause anomalies. (So common try/catch methods catch exceptions)

2. InputStream and OutputStream are abstract classes and cannot create objects of this type.

Four FileInputStream class

The FileInputStream class is a subclass of the InputStream class that handles data streams that use files as data input sources. How to use:

Mode 1:

 File Fin=new file ("D:/abc.txt"); Create a file

FileInputStream in=new FileInputStream (Fin); Read the contents of the file

Mode 2:

FileInputStream in=new

FileInputStream ("D:/abc.txt");

Mode 3:

  The constructor takes the FileDescriptor () object as its argument.

  FileDescriptor () fd=new filedescriptor ();

FileInputStream f2=new FileInputStream (FD);

Five FileOutputStream class

The FileOutputStream class is used to process data streams as data output purposes , a string that represents a file name, or a file or FileDescriptor object .

There are two ways to create a file stream object:

Mode 1:

File F=new file ("D:/abc.txt");

FileOutputStream out=new FileOutputStream (f);

Mode 2:

FileOutputStream out=new

FileOutputStream ("D:/abc.txt");

Method 3: The constructor takes the FileDescriptor () object as its argument.

FileDescriptor () fd=new filedescriptor ();

FileOutputStream f2=new FileOutputStream (FD);

Method 4: The constructor takes the file name as its first parameter, and the Boolean value as the second argument.

  FileOutputStream f=new FileOutputStream ("D:/abc.txt", true);

Attention:

  (1) When writing data in the file, overwrite the existing file if the file already exists, and (2) at the end of the read/write operation, call the Close method to close the stream.

Example: 2-1

Six File class

  the file class, like Inputstream/outputstream, belongs to a package that does not allow access to the contents of files .

  the file class is used primarily for naming files, querying file properties, and working with file directories .

Example: 2-2

Seven Construct another stream from one stream

The Java Stream class provides a structured approach, such as the underlying stream and the high-level filtering stream.

Instead of reading from the input device, the high-level stream reads from the other stream. The same high-level output stream is not written to the output device, but to other streams.

Using "layered objects (layered objects)", the practice of adding functionality to a single object dynamically and transparently, is known as decorator Pattern. The decorator mode requires that all objects that are wrapped outside the original object must have exactly the same interface. This makes the usage of decorator very transparent-the message passed to it is always the same regardless of whether the object has been decorate. This is why the Java I/O class library has a "filter" Class: The Abstract "Filter" class is the base class for all decorator. The decorator pattern is often used in situations where the number of classes can be unrealistic if you use inheritance to address a variety of needs. The Java I/O class library needs to provide a combination of many functions, so the decorator mode has its niche.

Classes that define decorator class interfaces for InputStream and OutputStream, respectively, are FilterInputStream and Filteroutputstream.

Types of FilterInputStream

Class

Function

Parameters of the constructor function

Usage

DataInputStream

Use with DataOutputStream so you can read primitives from the stream in a "portable way (Portable fashion)" (Int,char,long, etc.)

InputStream

Contains a complete set of interfaces for reading primitive data.

Bufferedinputstream

Use this class to solve the "physical read every time you want to use data" question . You mean "with a buffer." "

InputStream, and the capacity of the optional buffer

It does not provide an interface by itself, it simply provides a buffer. You need to connect to a "object with an interface (interface objects)".

Linenumberinputstream

Trace the line number of the input stream, with the Getlinenumber () and Setlinenumber (int) methods

InputStream

Just add a line number, so you have to connect an "object with an interface".

Pushbackinputstream

There is a "clamp single-byte" buffer (has a one byte push-back buffer) so you can press back the last byte you read.

InputStream

A scanner that is used primarily for compilers. may be designed for Java-enabled compilers. There are not many opportunities to use.

Types of Filteroutputstream

Class

Function

Parameters of the constructor function

Usage

DataOutputStream

Use with DataInputStream so you can write primitive in a "portable way (Portable fashion)" (int, char, long, etc.)

OutputStream

Includes a full set of interfaces for writing primitive data.

PrintStream

Responsible for generating formatted outputs (formatted output). Dataoutputstrem is responsible for the storage of data, while PrintStream is responsible for displaying the data.

A outputstream and an optional Boolean value. This Boolean value indicates whether to empty the buffer after the newline character.

Should be the final cladding of the OutputStream object. There are many opportunities to use.

Bufferedoutputstream

Use this class to solve the "every time you write data into the stream, you have to do the physical operation" problem. That is, "use buffer". Clears the buffer with flush ().

OutputStream, and an optional buffer size

itself does not provide an interface, just adds a buffer. You need to link an object that has an interface.

  The DataInputStream class object can read various types of data.

DataOutputStream class objects can write various types of data ;

  when you create both types of objects, you must make the newly created object point to the Parameter object in the constructor . For example:

FileInputStream in=new FileInputStream ("D:/abc.txt");

DataInputStream din=new datainputstream(in);

7.2Bufferinputstream and Bufferoutputstream

  allows the program to read data from a stream one byte at a time without slowing down the performance of the system .

Bufferinputstream defines two types of constructors

(1) Bufferinputstream b= new Bufferinputstream(in);

(2) Bufferinputstream b=new bufferinputstream(in,size)

 The second parameter indicates the size of the specified buffer .

There are also two kinds of constructors for the same bufferoutputstream. Writes data to a stream one byte at a time.

7.3PrintStream

Used to write text or basic types

Two constructor methods:

PrintStream ps=new PrintStream (out);

PrintStream ps=new PrintStream (out, AutoFlush)

The second parameter is a Boolean value that controls whether Java refreshes the output stream each time the line break is output.

Eight Reading and writing of character streams

Java.io.Reader and Java.io.InputStream make up the Java input class. Reader is used to read 16-bit characters, which are Unicode-encoded characters, while InputStream is used to read ASCII characters and binary data.

Reader Architecture

(1) FileReader

FileReader is primarily used to read character files, using the default character encoding, with three constructors:

--Use the file name as a string

FileReader f=new FileReader ("C:/temp.txt");

--The constructor functions the file object as its argument .

File F=new file ("C:/temp.txt");

FileReader f1=new FileReader (f);

-- The constructor takes the FileDescriptor object as a parameter

FileDescriptor () fd=new filedescriptor ()

FileReader f2=new FileReader (FD);

(2) CharArrayReader

The character array is used as the input stream, and the constructor is:

  Public CharArrayReader (char[] ch);

(3) StringReader

To read a string, the constructor is as follows:

  Public StringReader (String s);

(4) InputStreamReader

Reads bytes from the input stream, converting them to characters.

 Public InputStreamReader (InputStream are); (1 kanji characters require 2 bytes, 1 English characters require 1 bytes)

(5) FilterReader

Allow filtering of character streams

  Protected FilterReader (Reader R);

(6) Bufferreader

Accepts the reader object as a parameter and adds a character buffer to it, using the ReadLine () method to read a row.

  Public Bufferreader (Reader R);

Writer class architecture

(1) FileWrite

  writes character type data to a file, using the default character encoding and buffer size.

  Public FileWrite (file f);

(2) Chararraywrite ()

Use the character buffer as the output.

public Chararraywrite ();

(3) Printwrite

Generate formatted output

Public PrintWriter (OutputStream OS);

(4) Filterwriter

  Used to write a stream of filtered characters

Protected Filterwriter (Writer W);

Types of Filteroutputstream

Class

Function

Parameters of the constructor function

Usage

DataOutputStream

Use with DataInputStream so you can write primitive in a "portable way (Portable fashion)" (int, char, long, etc.)

OutputStream

Includes a full set of interfaces for writing primitive data.

PrintStream

Responsible for generating formatted outputs (formatted output). Dataoutputstrem is responsible for the storage of data, while PrintStream is responsible for displaying the data.

A outputstream and an optional Boolean value. This Boolean value indicates whether to empty the buffer after the newline character.

Should be the final cladding of the OutputStream object. There are many opportunities to use.

Bufferedoutputstream

Use this class to solve the "every time you write data into the stream, you have to do the physical operation" problem. That is, "use buffer". Clears the buffer with flush ().

OutputStream, and an optional buffer size

itself does not provide an interface, just adds a buffer. You need to link an object that has an interface.

The DataInputStream class object can read various types of data.

DataOutputStream class objects can write various types of data;

When you create both types of objects, you must make the newly created object point to the Parameter object in the constructor. For example:

FileInputStream in=new FileInputStream ("D:/abc.txt");

DataInputStream din=new DataInputStream (in);

Turn Java input and output stream details (very detailed)

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.