Java Programming Ideas Learning (13) Java I/O

Source: Internet
Author: User

In Java, a stream is used to process the input and output operations of a program, and the flow is an abstract concept that encapsulates the underlying details of the program data in the input interchange. In the Javaio, stream is divided into byte stream and character stream, the byte stream is mainly used to deal with the binary format data such as image, audio and video, and the character stream is mainly used to deal with the input and output of text characters and other types.

1. Byte input stream InputStream

Input stream InputStream is responsible for generating input from various data/file sources, including: arrays, strings, files, pipelines, a series of other types of streams, and streams generated by network connections, and so on.

Main types of common byte input streams:

(1). Bytearrayinputstream byte array input stream:

Main function: Allow memory cache as input stream.

The bytearrayinputstream contains an internal buffer that contains bytes read from the stream. The internal counter tracks the next byte to be provided by the read () method.

Note: Closing Bytearrayinputstream is not valid, and methods in this class can still be called after the stream is closed, without generating any ioexception.

(2). FileInputStream file input stream:

Main function: Obtain input bytes from a file in the file system for reading the raw byte stream of the data sub-class of the image. To read a character stream, use FileReader.

(3). PipedInputStream Pipeline Transmission Inflow:

Main function: Together with the pipeline output flow to form an input and output pipeline, is the data input port of the pipeline.

The pipeline input stream should be connected to the pipeline output flow, and the pipeline input stream provides all the data bytes to write to the pipeline output flow. Typically, this data has a thread that reads from the PipedInputStream object and other threads write it to the appropriate PipedOutputStream object.

Note: PipedInputStream and PipedOutputStream objects are not recommended to use single threaded because this may deadlock the thread. The pipe input stream contains a buffer that can be separated from the read and write operations within the bounds of the buffer, and is considered corrupted if the thread that first connected the pipeline output flow provides data bytes no longer exists.

(4). Sequenceinputstream Sequential Input stream:

Important function: Convert two or more input stream objects into a single input stream object.

Sequenceinputstream represents a logical concatenation relationship of other input streams, starting from an ordered collection of input streams and reading from the first input stream until the end of the file is reached, then reading from the second input stream, and so on until the end of the file containing the last input stream is reached.

(5). FilterInputStream Filter Input stream:

Main features: Includes other input streams, which are used as their basic data sources, which can transmit data directly or provide some additional functionality.

The common FilterInputStream is the DataInputStream data input stream, which is used primarily to allow the program to read Java base data types from the underlying input stream in a machine-independent manner. Its common methods are Readint (), Readboolean (), ReadChar (), and so on.

2. Byte output stream OutputStream:

Corresponds to the byte input stream, the byte output stream is responsible for the byte type data to the output of the destination file or device. A common byte output stream is as follows:

(1). Bytearrayoutputstream byte array output stream:

Main function: Create a buffer in memory to put the received data into the memory buffer.

The Bytearrayoutputstream implements an output stream in which the data is written to a byte array. Buffers grow automatically as data is written, and data can be obtained using the Tobytearray () and ToString () methods.

Note: Similar to Bytearrayinputstream, closing Bytearrayoutputstream is also invalid, and methods in this class can still be called after the stream is closed, without generating any ioexception.

(2). FileOutputStream file output stream:

Primary function: Writes data to the specified file.

The file output stream is an output stream used to write data to file or FileDescriptor, used to write raw byte streams such as data, and to write a stream of characters, use FileWriter.

(3). PipedOutputStream Pipeline output stream:

Main function: Connect pipeline to create communication pipeline, pipeline output stream is the pipeline data output.

(4). Filteroutputstream Filter Output stream:

Main function: Used for the existing output stream as its basic data receiver, you can transfer data directly or provide some additional processing.

The common Filteroutputstream is the DataOutputStream data output stream, which allows the program to write Java base data types in an appropriate manner to the output stream. Its common methods are Writeint (INTV), Writechar (int v), WriteByte (String s), and so on.

3. Character Stream:

The byte stream in Java can only be used for bytes type data, that is, support for processing 8-bit data types, since Java is a Unicode code, that is, two bytes represent a character, so after JDK1.1 provided a character stream reader and writer.

Character stream related common classes are as follows:

(1). Reader:

Abstract class for reading a string stream, the subclass must implement only reader (Char[],int, int) and close ().

(2). InputStreamReader:

is a converter that converts a byte input stream into a character input stream, which reads the bytes and decodes them to characters using the specified character set. That is, the byte-to-character.

The character set it uses can have a name specified or explicitly given, or it can use the default character set of the platform.

(3). Writer:

Abstract class for writing stream of characters, subclasses must implement only write (char[],int, int) and close ().

(4). OutputStreamWriter:

is a converter that converts a character output stream to a byte output stream, which encodes the characters of the inflow into bytes using the specified character set. That is, the character-to-byte.

4. Comprehensive use of various streams of Java IO:

The various streams in Java Io, rarely used alone, are often combined together to meet specific needs and be effective. Examples are as follows:

(1). Use buffered streams to read files:

1 ImportJava.io.*; 2   3  Public classbufferedinputfile{4      Public StaticString read (string filename)throwsioexception{5         //buffered character input stream6BufferedReader in =NewBufferedReader (Newfilereader (filename)); 7 String S; 8StringBuilder SB =NewStringBuilder (); 9     //every time you read a line in a fileTenwhile ((s = in.readline ())! =NULL){   OneSb.append (S +"\ n");  A }   - In.close ();  - returnsb.tostring ();  the }   -  Public Static voidMain (string[] args)throwsioexception{ - System.out.println (Read ("Bufferedinputfile.java"));  - }   +}

(2). Read the In-memory string:

1 ImportJava.io.*; 2   3  Public classmemoryinput{4      Public Static voidMain (string[] args)throwsioexception{5         //wrapping a string as a character input stream6StringReader in =NewStringReader (7 bufferedinputfile.read ("Bufferedinputfile.java")); 8         intC; 9         //reading characters from a character input streamTen          while((c = = In.read ())! =-1){   OneSystem.out.println ((Char) c);  A }   - }   -}

(3). Data input/output stream:

1 ImportJava.io.*; 2   3  Public classdatainputoutput{4      Public Static voidMain (string[] args) thows ioexception{5DataOutputStream out =NewDataOutputStream (NewBufferedoutputstream (6 NewFileOutputStream ("Data.txt")); 7Out.writedouble (3.14159); 8 Out.writeutf ("That is Pi"); 9Out.writedouble (1.41413);TenOut.writeutf ("Square root of 2");  One Out.close ();  ADataInputStream in =NewDataInputStream (NewBufferedinputstream ( - NewFileOutputStream ("Data.txt"));  - System.out.println (In.readdouble ());  the System.out.println (In.readutf ());  - System.out.println (In.readdouble ());  - System.out.println (In.readutf ());  - }   +}

Output Result:

3.14159

That is pi

1.41413

Square Root of 2

(4). text File output stream:

1 ImportJava.io.*; 2   3  Public classtextfileoutput{4     //Output File name5     StaticString file ="Basicfileoutput.out"; 6      Public Static voidMain (string[] args)throwsioexception{7         //wraps a string into a string input stream and then wraps the string input stream into a buffered character input stream8BufferedReader in =NewBufferedReader (NewStringReader9 (Bufferedinputfile.read ("Textfileoutput.java"))); Ten         //character output stream OnePrintWriter out =NewPrintWriter (NewBufferedWriter (NewFileWriter (file));  A         intLineCount = 1;  - String S;  -while ((s = in.readline ())! =NULL){   theOut.println (linecount++ + ":" +s);  - }   - Out.close ();  - }   +}

(5). binary file read and write:

1 ImportJava.io.*; 2   3  Public classbinaryfileoutput{4     //Output File name5     StaticString file ="Binaryfileoutput.out"; 6      Public Static voidMain (string[] args)throwsioexception{7         //wraps a string into a string input stream and then wraps the string input stream into a buffered character input stream8Bufferedinputstream in =NewBufferedinputstream (9 NewFileInputStream ("Testfile.png")); Ten         //character output stream OneBufferedoutputstream out =NewBufferedoutputstream ( A Newfileoutputstream (file));  -         byte[] buf =New byte[1024];  -         intN;  thewhile ((n = in.read (buf)) > 0){   -Out.write (buf, 0, N);  - }   - Out.close ();  + }   -}

Java Programming Ideas Learning (13) Java I/O

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.