Streams in Java (concepts and examples)

Source: Internet
Author: User
Tags flush readline
first of all, what the stream is.

The flow is an abstract concept, is the abstraction of the input, in the Java program, the data input/output operation is in the "Flow" way. Devices can be files, networks, memory, and so on.

Flow has directionality, as for the input stream or output stream is a relative concept, generally with the program as a reference, if the flow of data to the device, we become the output stream, and vice versa we call the input stream.

The flow can be imagined as a "flow pipe", the flow is formed in the pipeline, the concept of the direction of nature appears.

When a program needs to read data from a data source, an input stream is opened and the data source can be a file, memory, or network, and so on. Conversely, when you need to write data to a data source destination, you also open an output stream, which can also be a file, memory, or network, and so on. What sorts of streams there are.

You can classify convection from different angles:

1. The processing of different units of data can be divided into: character streams, word throttling

2. Data flow direction is different, can be divided into: input stream, output stream

3. Different functions, can be divided into: node flow, processing flow

1. and 2. Are better understood, for the classification based on the function, you can understand so:

Node Flow: A node stream reads and writes data from a specific data source. That is, a node stream is a stream of direct manipulation of files, networks, etc., such as FileInputStream and FileOutputStream, that they read directly from a file or write a byte stream to a file.

Process flow: A "connection" provides a more powerful read and write capability to a program through the processing of data over existing streams (node flows or processing streams). The filter stream is created using an existing input stream or an output stream connection, which is a series of wrappers over the node stream. Bufferedinputstream and Bufferedoutputstream, for example, use existing node streams to construct, provide buffered read and write, improve read and write efficiency, and DataInputStream and DataOutputStream, Constructs with existing node streams to provide the ability to read and write basic data types in Java. They all belong to the filter stream.

Flow Structure Introduction:

All Java stream classes are in the Java.io package, and each inherits the following four types of abstract streams.

Word throttling Character streams
Input stream InputStream Reader
Output stream OutputStream Writer

1. Streams inherited from Inputstream/outputstream are used to input/output data to the program, and the units of the data are bytes (byte=8bit), such as graphs, dark nodes, and light-colored for processing streams.

2. Streams inherited from Reader/writer are used to input/output data to the program, and the units of the data are characters (2byte=16bit), such as graphs, dark nodes, and light-colored for processing streams.

Common Flow class Introduction:

Common types of node streams are:

The character stream of the file operation has filereader/filewriter, the word throttling has fileinputstream/fileoutputstream.

Common types of processing streams are:

Buffer flow: Buffer stream to "socket" on the corresponding node stream, the data read and write provides a buffering function, improve the reading and writing efficiency, colleagues added some new methods.

Byte buffer stream has bufferedinputstream/bufferedoutputstream, character Buffer stream has bufferedreader/bufferedwriter, The character Buffer stream provides a way to read and write a row ReadLine and newline methods.

For the output buffer stream, the data that is written is written to memory first, then the Flush method is used to brush the data in memory to the hard disk. Therefore, in the use of character buffer stream, we must first flush, and then close to avoid data loss.

Conversion Flow: A conversion between byte data and character data.

Only character streams are inputstreamreader/outputstreamwriter. Among them, InputStreamReader needs to InputStream "socket", outputstreamwriter need to be connected with OutputStream "".

Data flow: Provides the ability to read and write basic data types in Java.

DataInputStream and DataOutputStream inherit from InputStream and OutputStream respectively, requiring "sockets" on the InputStream and OutputStream types of node streams.

Object flow: Used to write objects directly.

The Stream class has ObjectInputStream and ObjectOutputStream, and the two methods are not the same, but the object to write is required, and the object must implement the serializable interface to declare that it can be serialized. Otherwise, you cannot read and write with the object stream.

Another keyword is more important, transient, because the property that is decorated by the modifier that implements the serializable interface is ignored when it is exported as an object stream.


code Example:

1, data stream write read data (basic type data int,boolean, etc.)

public void IOStream () throws IOException {

		 //data stream write-read data (base type data Int,boolean, etc.)
		 String filePath = Environment
		 . getExternalStorageDirectory ()
		 . GetAbsolutePath ()
		 + "/" + "A.txt";
		
		 The node stream FileOutputStream directly A.txt as the data source
		 fileoutputstream FileOutputStream = new FileOutputStream (filePath);
		 The filtered stream Bufferedoutputstream further decorates the node stream, providing a buffer to write
		 bufferedoutputstream bufferedoutputstream = new Bufferedoutputstream (
		 fileoutputstream);
		 The filter flow DataOutputStream further decorates the filter flow, making it provide the basic data type of write
		 dataoutputstream out = new DataOutputStream (bufferedoutputstream);
		 Out.writeint (3);
		 Out.writeboolean (true);
		 Out.writeutf ("1234ABCD test");
		 Out.flush ();
		 Out.close ();
		 The input node stream here, the filter stream exactly corresponds to the top output, the reader can extrapolate
		 datainputstream in = new DataInputStream (New Bufferedinputstream
		 FileInputStream (FilePath)));
		 System.out.println (In.readint ());
		 System.out.println (In.readboolean ());
		 System.out.println (In.readutf ());
		 In.close ();
}

2, Buffer stream write read Data

public void IOStream () throws IOException {
   
                //buffered stream write-read data
		String FilePath = Environment.getexternalstoragedirectory ()
				. GetAbsolutePath () + "/" + "Text.txt";
		File NewFile = new file (FilePath);
		String data = "Hello, android.2011";
		FileWriter write = new FileWriter (NewFile, true);
		BufferedWriter bufferedwriter = new BufferedWriter (write);
		Bufferedwriter.write (data);
		Bufferedwriter.newline ()//Line break

		/
		 * Refreshes the buffer of the stream.
		 * 
		 * key line of code. If this line of code is not added. Data is only guaranteed to exist in the buffer. No file was written in.
		 * 
		 * Add this line to write the data to the destination. 
		 * *
		
		bufferedwriter.flush ();
		Write.close ();
		Bufferedwriter.close ();

		
		FileReader FR = new FileReader (filePath);
		BufferedReader br = new BufferedReader (FR);
		String valuestring = null;
		while ((valuestring = Br.readline ())!= null) {
			System.out.println (valuestring);
		}

}

3, File stream (node stream) write-read data

public void IOStream () throws IOException {
   
                //file stream (node stream) write-read data
		String FilePath = Environment.getexternalstoragedirectory ()
		. GetAbsolutePath () + "/" + "txt.txt";
		File File = new file (FilePath);
		if (!file.exists ())
		{
			file.createnewfile ();	
		}
		
		FileOutputStream OutStream = new FileOutputStream (
				filePath);
		Outstream.write ("1234ABCD test". GetBytes ("Utf-8"));
		Outstream.close ();
		
		Read data reference data stream and buffer stream read data

}

Java flow of information, reprinted together to facilitate access to






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.