Java IO2: Byte stream

Source: Internet
Author: User

Input and output stream:

input/output, the data flows in the communication channel. The so-called "stream" refers to all data communication channels, the starting point and end point. The channel of information is a data stream. As long as the data from one place "flow" to another place, this data flow channel can be called Data flow.
input/output is relative to the program. There are two roles that the program plays when using data: One is the source and the other is the purpose. If the program is the source of the data stream, that is, the data provider, this data flow to the program is an "output data Flow" (data outflow from the program). If the program is the end of the data stream, the data flow is an "input data stream" (data from the program to the program)
is functionally divided into two main categories: input stream and output stream.
from the flow structure can be divided into byte stream ( Bytes as processing units or byte-oriented, and character streams (in characters as processing units or character-oriented characters).
Byte stream are based on InputStream and OutputStream, both abstract class, the input and output operations of a byte stream are implemented by subclasses of these two classes. The character stream is the newly added stream of input and output processing in character units after Java version 1.1, and the character stream input and output is based on abstract class reader and writer

• Need to declare: at the bottom, all inputs/outputs are in bytes. Character-based streaming is only a convenient and efficient way to handle characters.

Classification of streams

• Node Flow: A stream class that reads and writes from a specific place, such as a disk or a piece of memory area.
• Filter Flow: use node stream as input or output. The filtered stream is created using an existing input stream or an output stream connection.

Byte Stream and character stream

The Byte stream class (byte Streams) stream class is used to read and write 8-bit binary bytes to a character stream. Generally, the byte stream class is primarily used to read and write binary data such as images or sounds.
• Character Stream class (Character Streams) character Stream class is used to read and write 16-bit binary characters to a character stream.

Byte Streams Character Streams
InputStream Reader
OutputStream Writer

• Two basic streams are the input stream and the output stream. An object from which a series of bytes can be read is called an input stream. The object to which a series of bytes can be written is called the output stream.

Input stream

the logic for reading data is: Open a stream  while More Informationread Informationclose the stream

Output stream

the logic for writing data is: Open a stream  while More Informationwrite Informationclose the stream

The byte stream class takes InputStream and OutputStream as the top-level class, which are abstract classes

• Abstract classes InputStream and OutputStream define the key methods for implementing other flow classes. The two most important methods are read () and write (), which read and write each byte of the data. Two kinds of
Methods are defined as abstract methods in InputStream and OutputStream. They are overridden by a derived stream class.

OutputStream (byte output stream)

OutputStream is an abstract class that defines the Java streaming byte input pattern. All methods of the class return a void value and raise a ioexception in case of an error.

Three basic methods of writing
abstract void Write (int b): Writes a byte to the output stream.
void Write (byte[] b): Writes all the bytes in array b toward the output stream.
void Write (byte[] b, int off,int len): Writes the Len byte data in array b from offset off to the output stream.

Other methods
void Flush (): Flushes the output stream, forcing the output bytes in the buffer to be written out.
void Close (): Closes the output stream, releasing the system resources associated with this stream.

• By opening an output stream to the target, the program can write data to the external destination sequence. When the Java program needs to output the data to the peripheral, it can create an object of the appropriate OutputStream subclass type according to the different forms of the data to complete the connection with the peripheral, and then invoke the specific output method executing the Stream class object to implement the output operation to the corresponding peripheral.

FileOutputStream (file byte output stream)

Fileoutpustream should be the most common byte output stream in Java, which creates a class outputstream that can write bytes to a file, which is commonly constructed as follows:

1, FileOutputStream (String name)

2, FileOutputStream (file file)

3, FileOutputStream (file file, Boolean append)

The first two constructor methods are similar, the former input the absolute path of the file, the latter input the instance object, and the same as Randomaccessfile, recommend the latter. There is a difference in the third method of construction.

if true, then bytes'll is written to the end of the file rather than the beginning

That is, the original file has the content of the words will not be washed away, will be added on the basis of the original content.

 Public class OutputStreamTest1 {    publicstaticvoidthrows  Exception {         New File ("C:\\out.txt");         New true );         byte [] buffer = "Hello World". GetBytes ();        Os.write (buffer);        Os.close ();    }}

At this point, open "OUT.txt":

See the "OUT.txt" under the C drive, and the contents of the file are consistent with our writing.

InputStream (byte input stream)

InputStream is an abstract class that defines the Java streaming byte input pattern. All of the methods in this class will throw an abstract method provided by Ioexception,inputstream when it goes wrong:

Three basic reading methods
abstract int Read (): reads a byte of data and returns the read data if 1 is returned, indicating that the end of the input stream is read.
int read (byte[] b): reads data into a byte array and returns the number of bytes actually read. If 1 is returned, the end of the input stream is read.
int read (byte[] b, int off, int len): reads the data into a byte array and returns the number of bytes actually read. If 1 is returned, the end of the input stream is read. OFF specifies the starting offset where the data is stored in array B, and Len specifies the maximum number of bytes to read.

• Because the second Read method relies on the third read method, and the third read method is implemented by the first read method, only the first read method is related to the specific I/O device, which requires the InputStream subclass to be implemented.

Other methods

Long n: Skips n bytes in the input stream and returns the number of bytes actually skipped.
int available (): Returns the number of bytes that can be read without blocking.
void Close (): closes the input stream and frees the system resources associated with this stream.
void mark (int readlimit): A tag is placed at the current position of the input stream, and if the number of bytes read is greater than the value set by Readlimit, the stream ignores the token.
void Reset (): Returns to the previous tag.
Boolean marksupported (): Tests whether the current stream supports the mark and reset methods. Returns TRUE if supported, otherwise false is returned.

• By opening an input stream to a data source (file, memory, or network port), the program can read the data sequentially from the data source.

FileInputStream (file byte input stream)

FileInputStream is the most common byte input stream in Java, which creates a InputStream class that reads bytes from a file , and its two common construction methods are as follows:

1, FileInputStream (String name)

2, FileInputStream (file file)

The use of the latter is recommended.

 Public classInputstreamtest {
Public Static voidMain (string[] args)throwsException {File file=NewFile ("C:\\Test.txt"); InputStream is=Newfileinputstream (file); //cache, Bytes read first placed in cache byte[] buffer =New byte[200]; //the number of bytes actually read intLength = 0; while(length = is.read (buffer, 0, 200))! =-1) { //converts a read byte array into a stringString str =NewString (buffer, 0, length); System.out.println (str); } is.close (); }}

Run results

Heroes Come and go! But Legends is forever! Mainbachet The Legend of Eternity

Java IO2: Byte stream

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.