首页 > 代码库 > Java IO: InputStream

Java IO: InputStream


Java Io 

1Java IO Tutorial
2Java IO Overview
3Java IO: Files
4Java IO: Pipes
5Java IO: Networking
6Java IO: Byte & Char Arrays
7Java IO: System.in, System.out, and System.error
8Java IO: Streams
9Java IO: Input Parsing
10Java IO: Readers and Writers
11Java IO: Concurrent IO
12Java IO: Exception Handling
13Java IO: InputStream
14Java IO: OutputStream
15Java IO: FileInputStream
16Java IO: FileOutputStream
17Java IO: RandomAccessFile
18Java IO: File
19Java IO: PipedInputStream
20Java IO: PipedOutputStream
21Java IO: ByteArrayInputStream
22Java IO: ByteArrayOutputStream
23Java IO: FilterInputStream
24Java IO: FilterOutputStream
25Java IO: BufferedInputStream
26Java IO: BufferedOutputStream
27Java IO: PushbackInputStream
28Java IO: SequenceInputStream
29Java IO: DataInputStream
30Java IO: DataOutputStream
31Java IO: PrintStream
32Java IO: ObjectInputStream
33Java IO: ObjectOutputStream
34Java IO: Serializable
35Java IO: Reader
36Java IO: Writer
37Java IO: InputStreamReader
38Java IO: OutputStreamWriter
39Java IO: FileReader
40Java IO: FileWriter
41Java IO: PipedReader
42Java IO: PipedWriter
43Java IO: CharArrayReader
44Java IO: CharArrayWriter
45Java IO: BufferedReader
46Java IO: BufferedWriter
47Java IO: FilterReader
48Java IO: FilterWriter
49Java IO: PushbackReader
50Java IO: LineNumberReader
51Java IO: StreamTokenizer
52Java IO: PrintWriter
53Java IO: StringReader
54Java IO: StringWriter

Java IO: InputStream

 
By Jakob Jenkov
 Connect with me: 
Rate article:
<iframe frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1416446177219" name="I0_1416446177219" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&origin=http%3A%2F%2Ftutorials.jenkov.com&url=http%3A%2F%2Ftutorials.jenkov.com%2Fjava-io%2Finputstream.html&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.zh_CN.0KI2lcOUxJ0.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPnLWTRWXjQ3yHtGTFSsUVyRcOV5g#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1416446177219&parent=http%3A%2F%2Ftutorials.jenkov.com&pfname=&rpctoken=27601238" data-gapiattached="true" style="position: absolute; top: -10000px; width: 450px; margin: 0px; border-style: none;"></iframe>
Share article:
<iframe frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I1_1416446177224" name="I1_1416446177224" src="https://apis.google.com/se/0/_/+1/sharebutton?plusShare=true&usegapi=1&action=share&height=24&annotation=none&origin=http%3A%2F%2Ftutorials.jenkov.com&url=http%3A%2F%2Ftutorials.jenkov.com%2Fjava-io%2Finputstream.html&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.zh_CN.0KI2lcOUxJ0.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPnLWTRWXjQ3yHtGTFSsUVyRcOV5g#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh%2Conload&id=I1_1416446177224&parent=http%3A%2F%2Ftutorials.jenkov.com&pfname=&rpctoken=22162960" data-gapiattached="true" style="position: absolute; top: -10000px; width: 450px; margin: 0px; border-style: none;"></iframe>
Tweet

The InputStream class is the base class (superclass) of all input streams in the Java IO API. InputStreamSubclasses include the FileInputStreamBufferedInputStream and the PushbackInputStream among others. To see a full list of InputStream subclasses, go to the bottom table of the Java IO Overview page.

InputStreams and Sources

An InputStream is typically always connected to some data source, like a file, network connection, pipe etc. This is also explained in more detail in the Java IO Overview text.

Java InputStream Example

Java InputStream‘s are used for reading byte based data, one byte at a time. Here is a Java InputStreamexample:

InputStream inputstream = new FileInputStream("c:\\data\\input-text.txt");

int data = http://www.mamicode.com/inputstream.read();>

This example creates a new FileInputStream instance. FileInputStream is a subclass of InputStream so it is safe to assign an instance of FileInputStream to an InputStream variable (the inputstream variable).

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

From Java 7 you can use the try-with-resources construct to make sure the InputStream is properly closed after use. The link in the previous sentence points to an article that explains how it works in more detail, but here is a simple example:

try( InputStream inputstream = new FileInputStream("file.txt") ) {

    int data = http://www.mamicode.com/inputstream.read();>

Once the executing thread exits the try block, the inputstream variable is closed.

read()

The read() method of an InputStream returns an int which contains the byte value of the byte read. Here is anInputStream read() example:

int data = http://www.mamicode.com/inputstream.read();>

You can case the returned int to a char like this:

char aChar = (char) data;

Subclasses of InputStream may have alternative read() methods. For instance, the DataInputStream allows you to read Java primitives like int, long, float, double, boolean etc. with its corresponding methods readBoolean(),readDouble() etc.

End of Stream

If the read() method returns -1, the end of stream has been reached, meaning there is no more data to read in theInputStream. That is, -1 as int value, not -1 as byte or short value. There is a difference here!

When the end of stream has been reached, you can close the InputStream.

read(byte[])

The InputStream class also contains two read() methods which can read data from the InputStream‘s source into a byte array. These methods are:

  • int read(byte[])
  • int read(byte[], int offset, int length)

Reading an array of bytes at a time is much faster than reading one byte at a time, so when you can, use these read methods instead of the read() method.

The read(byte[]) method will attempt to read as many bytes into the byte array given as parameter as the array has space for. The read(byte[]) method returns an int telling how many bytes were actually read. In case less bytes could be read from the InputStream than the byte array has space for, the rest of the byte array will contain the same data as it did before the read started. Remember to inspect the returned int to see how many bytes were actually read into the byte array.

The read(byte[], int offset, int length) method also reads bytes into a byte array, but starts at offsetbytes into the array, and reads a maximum of length bytes into the array from that position. Again, theread(byte[], int offset, int length) method returns an int telling how many bytes were actually read into the array, so remember to check this value before processing the read bytes.

For both methods, if the end of stream has been reached, the method returns -1 as the number of bytes read.

Here is an example of how it could looke to use the InputStream‘s read(byte[]) method:

InputStream inputstream = new FileInputStream("c:\\data\\input-text.txt");

byte[] data      = http://www.mamicode.com/new byte[1024];>

First this example create a byte array. Then it creates an int variable named bytesRead to hold the number of bytes read for each read(byte[]) call, and immediately assigns bytesRead the value returned from the firstread(byte[]) call.

Inside the while loop the doSomethingWithData() method is called, passing along the data byte array as well as how many bytes were read into the array as parameters. At the end of the while loop data is read into the bytearray again.

It should not take much imagination to figure out how to use the read(byte[], int offset, int length)method instead of read(byte[]). You pretty much just replace the read(byte[]) calls with read(byte[], int offset, int length) calls.

mark() and reset()

The InputStream class has two methods called mark() and reset() which subclasses of InputStream may or may not support.

If an InputStream subclass supports the mark() and reset() methods, then that subclass should override themarkSupported() to return true. If the markSupported() method returns false then mark() and reset() are not supported.

The mark() sets a mark internally in the InputStream which marks the point in the stream to which data has been read so far. The code using the InputStream can then continue reading data from it. If the code using theInputStream wants to go back to the point in the stream where the mark was set, the code calls reset() on theInputStream. The InputStream then "rewinds" and go back to the mark, and start returning (reading) data from that point again. This will of course result in some data being returned more than once from the InputStream.

The methods mark() and reset() methods are typically used when implementing parsers. Sometimes a parser may need to read ahead in the InputStream and if the parser doesn‘t find what it expected, it may need to rewind back and try to match the read data against something else.
















Java IO: InputStream