Input and Output streams in Java

Source: Internet
Author: User
  1. From http://blog.csdn.net/aflylove/article/details/1338549
  2. A large part of network programs is simple input and output, that is, moving bytes from one system to another. Bytes are bytes. To a large extent, the data sent by the read server is no different from the data read from the file. There is no difference between transmitting data to the customer and writing a file.

In Java, input and output are organized differently from most other languages. It is built on a stream. Different Basic stream classes (such as Java. Io. fileinputstream and sun.net. telnetoutputstream) are used to read and write specific data resources. However, all basic output streams read data using the same basic method.

A filter stream can be connected to an input stream or an output stream. It can modify the data that has been read or written to (for example, encrypted or compressed data), or simply provide additional methods to convert the data that has been read or written to another format.

Reader and writer can also link to the input stream and output stream to allow the program to read and write text (that is, characters) rather than bytes. If used correctly, reader and writer can handle multiple types of character encoding, including multi-byte character sets such as sjis and UTF-8.

 

I. output stream

The basic output stream of Java is Java. Io. outputstream.

Public abstract class outputstream

 

N public abstract void write (int B) throws ioexception

N public void write (byte [] data) throws ioexception

N public void write (byte [] data, int offset, int length) throws ioexception

N public void flush () throws ioexception

N public void close () throws ioexception

The subclass of outputstream uses these methods to write data to the specified media.

 

I always believe that we understand why they exist, so we will better remember them. Well, let's start with the origin of the methods of the outputstream class.

Public abstract void write (int B) throws ioexception

 

The basic method of outputstream is write (int B ). This method treats integers between 0 and 255 as variables and writes the corresponding bytes to an output stream. This method declaration is an abstract method because the subclass needs to change it to process specific media. For example, bytearrayoutputstream can use pure Java code to copy bytes to its array to implement the method. However, fileoutputstream requires code that understands how to write data to files on the host platform. Note: although this method regards the integer value as a variable, it actually writes an unsigned byte. Java does not have an unsigned byte data type, so an integer is used here. The real difference between unsigned bytes and symbolic bytes is the compiler's interpretation of them. Both are composed of eight digits, and when you use write (int
B) when writing an int to a network connection stream, only 8-bit data is transmitted. If an int that exceeds the range 0-is passed to write (int B), the low byte of the number is written, ignore the remaining three bytes (we all know that Java's Int Is 4 bytes, And the essence here is to convert int to byte ).

 

Public void write (byte [] data) throws ioexception and public void write (byte []
Data, int offset, int length) throws ioexception

 

Writing one byte at a time is usually inefficient. Therefore, most TCP/IP programs store data in a buffer with a certain length, that is, accumulating bytes in the memory. Only when a certain number of bytes are accumulated or a certain period of time has elapsed, to the destination. Therefore, write (byte [] data) and write (byte [] data, int offset, int length) are generated in this way.

 

Public void flush () throws ioexception

 

We can implement the buffer operation in the software or directly in the Java code, or in the network hardware. As if bufferedoutputstream or bufferedwriter is linked to the bottom layer to implement stream buffering. Therefore, if data is being written, refresh the output stream. For example, if a 300-byte request has been written to an HTTP server of HTTP keep-alive, you usually want to wait for a response between sending more data. However, if the output stream has a 1024-byte buffer, the stream may be waiting for more data to arrive before sending data to the buffer, but the data does not seem to arrive, because they have not been sent, but the buffer Stream does not send data to the server, unless it obtains more data from the bottom layer, but the bottom layer does not send more data, unless it obtains data from the server, and the server does not send data, unless it obtains data retained in the buffer (deadlock !), The flush () method can solve this deadlock, because even if the buffer zone is not full, it will force the request to implement the buffer operation of the stream to transfer data. Note: whether or not the stream is buffered depends on how you obtain the reference pointing to the stream (for example, whether or not you want to buffer system. Out, it will be buffered ). If the refresh stream needs to be refreshed, it must be refreshed, but if the refresh fails, it will lead to unpredictable and non-repeated program suspension (flush () returns void ), if you do not know the issue of suspension in advance, it is difficult to solve the problem. Therefore, you should refresh them immediately before closing all streams. Otherwise, the remaining data in the buffer may be lost before closing the stream.

 

Public void close () throws ioexception

 

Finally, after the stream is used up, the close () method should be called to close the stream. It releases all resources related to the stream, such as file handles or ports. Once the output stream is closed, writing data to it triggers an ioexception. However, some types may allow certain operations on objects. If a closed bytearrayoutputstream can still be converted into an actual byte array, and a closed digestoutputstream can still return its summary.

 

Ii. input stream

The basic input stream of Java is Java. Io. inputstream.

Public abstract class inputstream

N public abstract int read () throws ioexception

N public int read (byte [] data) throws ioexception

N public int read (byte [] data, int offset, int length) throws ioexception

N public long SKIP (long n) throws ioexception

N public int available () throws ioexception

N public void close () throws ioexception

The specific subclass of inputstream uses these methods to read data from the specified media. However, no matter what type of resource is read, you can only use these six methods. Sometimes you may not even know which type of stream is reading data. For example, in the sun.net package, telnetinputstream is a class not described in the document. The instance of telnetinputstream is returned by multiple methods in the java.net package, such as the openstram () method of java.net. URL. However, these methods only declare the returned inputstream, rather than the more explicit subclass telnetinputstream, which is where polymorphism is working. Subclass instances can be used transparently as superclasses.

Now, let's explain the origin of the method.

Public abstract void read () throws ioexception

 

The basic method of the inputstream class is the read () method without parameters (this is different from outputstream ). This method reads a single byte of data from the input stream resource and returns the data as the number between 0 and 255. If-1 is returned, it indicates the end of the stream. Because Java does not have an unsigned byte data type, data is returned as an integer. The read () method waits for and blocks the execution of the latter and the code until a byte of data is obtained and is ready to read the byte. Therefore, input and output may be quite slow. If you need to complete other important tasks, you 'd better try to put I/O in their own threads. The read () method is declared as an abstract method because the subclass needs to change it to process specific media. Example

Byte [] input = new byte [10];

For (INT I = 0; I

Int B = in. Read ();

If (B =-1) break;

Input [I] = (byte) B;

}

Although the read () method only reads bytes, it returns an integer value. Therefore, a type conversion process is required before the results are stored in a byte array. Of course, this will generate a signed byte between-128 and 127, instead of an unsigned byte between 0 and 255 returned by the read () method. However, as long as you know whether to use unsigned or signed bytes, there will be no major problems. Therefore, we can convert a signed byte to an unsigned byte (only integers ranging from 0 to can be stored in a byte type variable in Java ).

Int I = B> = 0? B: 256 + B;

It takes a lot of time to explain how to handle the byte type returned by read () and Java. Please note that if you are still interested in the original data type of Java, you can take a look at my original data type learning notes (unfinished ).

 

 

Public int read (byte [] data) throws ioexception, public int read (byte []
Data, int offset, int length) throws ioexception

 

Reading one byte at a time and writing one byte at a time are inefficient. Therefore, read (byte [] data) and read (byte [] data, int offset, int length) it is also generated. These two methods fill multiple bytes read from the stream into a specified array. Note: These operations to populate the array may not be successful. A common situation is that a read attempt will not fail completely or succeed completely. It may read part of the request data, not all bytes. For example, when only 512 bytes have actually arrived at the server, the user may try to read 1024 bytes from a network stream, while other bytes are still being transferred, and these bytes will eventually arrive at the server, but it is not available at the time of arrival. Therefore, the multibyte read method returns the actual number of bytes read. Example

Byte [] input = new byte [1024];

Int bytesread = in. Read (input );

The code snippet tries to read 1024 bytes from inputstream in to the array input. However, if only 512 bytes are available, these bytes are all the bytes to be read, and the bytesread value is set to 512. But what should we do to ensure that all the bytes are actually read? View

Int bytesread = 0;

Int bytetoread = 1024;

Byte [] input = new byte [bytetoread];

While (bytesread

Bytesread + = in. Read (input, bytesread, bytetoread-bytesread );

}

Public int available () throws ioexception

 

If you do not want to read data for some reason, you can use the available () method to return the minimum number of bytes that can be read, unless all the data you want can be obtained immediately, in fact, more bytes can be read, but the number of bytes that can be read must be at least the same as the number of bytes returned by available.

Look at the example

Int bytesavailable = in. Available ();

Byte [] input = new byte [bytesavailable];

Int bytetead = in. Read (input, 0, bytesavailable );

// Other code

Here we can assert that bytesread is exactly equal to bytesavailable, but we cannot assert that bytesread> 0, because available () returns 0.

When the stream ends:

Available () returns 0;

Read (byte [] data, int offset, int length) usually returns-1;

When the Stream does not end, the number of bytes can be read, that is, when the value of available () is 0

Read (byte [] data, int offset, int length) ignores the end of the stream and returns 0;

 

Public long SKIP (long n) throws ioexception

 

In rare cases, users may want to skip the data instead of reading them. The Skip () method implements this function. This method is more useful in reading data from files, while it is less useful in network connection streams. Because the network connection stream is ordered and usually slow, it takes less time to read data than to skip data. Files can be accessed randomly, so we can simply redirect data by relocating the file pointer, rather than skipping every byte.

 

Public void close () throws ioexception

 

Like the output stream, after the program uses the input stream, it should call the close () method to close the input stream (remember ). This method releases all resources related to the input stream, such as the file handle and port. Ioexception is triggered when the input stream is closed and data is read from it. However, some types of streams may still allow certain operations on objects. For example, you generally do not want to obtain a message digest from Java. Security. digestinputstream unless you have read all the data and disabled the input stream.

 

You may also ask why there are three other methods available.

Public void mark (INT readaheadlimit)

Public void reset () throws ioexception

Public Boolean marksupported ();

These methods allow the program to back up and re-read data that has been read. To implement this function, you need to use the mark () method to mark the current position in the input stream. In the future, you can use the reset () method to re-locate the stream to the mark, subsequent reads will return the data starting from the mark. However, the stream positioning point cannot be any longer from the mark point to the re-move. The number of bytes that can be read before the mark is located again is determined by the readaheadlimit variable of mark. The ioexception will be triggered at any specified time. The input stream can only have one tag. If the second tag is marked, the first tag will be overwritten. In fact, both marking and resetting locations are achieved by storing each byte from the marking position in the internal buffer zone. Not all input streams support marking and resetting positions. Therefore, you must use the marksupported () method to check the settings.

In fact, it does not support marking and resetting more streams than those that support them. Master elliotte Rusty Harold thinks that the design standards of these methods are not high. It is a rather poor idea to combine functionality with an abstract superclass that many or even most sub-classes are unavailable. It is best to put these three methods in different interfaces. It is a traditional and non-object-oriented solution to provide functional detection similar to the marksupported () method during runtime. The object-oriented method embeds the method into the object-oriented system through interfaces and classes, so as to detect all the streams during compilation.

Java. Io always supports the marked Input streams: bufferedinputstream and bytearrayinputstream.

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.