Java IO: InputStream

简介: Java Io 1Java IO Tutorial2Java IO Overview3Java IO: Files4Java IO: Pipes5Java IO: Networking6Java IO: Byte & Char Arrays7Java IO: System.


Java Io 

1 Java IO Tutorial
2 Java IO Overview
3 Java IO: Files
4 Java IO: Pipes
5 Java IO: Networking
6 Java IO: Byte & Char Arrays
7 Java IO: System.in, System.out, and System.error
8 Java IO: Streams
9 Java IO: Input Parsing
10 Java IO: Readers and Writers
11 Java IO: Concurrent IO
12 Java IO: Exception Handling
13 Java IO: InputStream
14 Java IO: OutputStream
15 Java IO: FileInputStream
16 Java IO: FileOutputStream
17 Java IO: RandomAccessFile
18 Java IO: File
19 Java IO: PipedInputStream
20 Java IO: PipedOutputStream
21 Java IO: ByteArrayInputStream
22 Java IO: ByteArrayOutputStream
23 Java IO: FilterInputStream
24 Java IO: FilterOutputStream
25 Java IO: BufferedInputStream
26 Java IO: BufferedOutputStream
27 Java IO: PushbackInputStream
28 Java IO: SequenceInputStream
29 Java IO: DataInputStream
30 Java IO: DataOutputStream
31 Java IO: PrintStream
32 Java IO: ObjectInputStream
33 Java IO: ObjectOutputStream
34 Java IO: Serializable
35 Java IO: Reader
36 Java IO: Writer
37 Java IO: InputStreamReader
38 Java IO: OutputStreamWriter
39 Java IO: FileReader
40 Java IO: FileWriter
41 Java IO: PipedReader
42 Java IO: PipedWriter
43 Java IO: CharArrayReader
44 Java IO: CharArrayWriter
45 Java IO: BufferedReader
46 Java IO: BufferedWriter
47 Java IO: FilterReader
48 Java IO: FilterWriter
49 Java IO: PushbackReader
50 Java IO: LineNumberReader
51 Java IO: StreamTokenizer
52 Java IO: PrintWriter
53 Java IO: StringReader
54 Java 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&amp;origin=http%3A%2F%2Ftutorials.jenkov.com&amp;url=http%3A%2F%2Ftutorials.jenkov.com%2Fjava-io%2Finputstream.html&amp;gsrc=3p&amp;ic=1&amp;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&amp;id=I0_1416446177219&amp;parent=http%3A%2F%2Ftutorials.jenkov.com&amp;pfname=&amp;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&amp;usegapi=1&amp;action=share&amp;height=24&amp;annotation=none&amp;origin=http%3A%2F%2Ftutorials.jenkov.com&amp;url=http%3A%2F%2Ftutorials.jenkov.com%2Fjava-io%2Finputstream.html&amp;gsrc=3p&amp;ic=1&amp;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&amp;id=I1_1416446177224&amp;parent=http%3A%2F%2Ftutorials.jenkov.com&amp;pfname=&amp;rpctoken=22162960" data-gapiattached="true" style="position: absolute; top: -10000px; width: 450px; margin: 0px; border-style: none;"></iframe>

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 = inputstream.read();
while(data != -1) {
  //do something with data...
  doSomethingWithData(data);

  data = inputstream.read();
}
inputstream.close();

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 = inputstream.read();
    while(data != -1){
        System.out.print((char) data);
        data = 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 = 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      = new byte[1024];
int    bytesRead = inputstream.read(data);

while(bytesRead != -1) {
  doSomethingWithData(data, bytesRead);

  bytesRead = inputstream.read(data);
}
inputstream.close();

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.
















目录
相关文章
|
3月前
|
存储 Java
【IO面试题 四】、介绍一下Java的序列化与反序列化
Java的序列化与反序列化允许对象通过实现Serializable接口转换成字节序列并存储或传输,之后可以通过ObjectInputStream和ObjectOutputStream的方法将这些字节序列恢复成对象。
|
19天前
|
存储 缓存 Java
java基础:IO流 理论与代码示例(详解、idea设置统一utf-8编码问题)
这篇文章详细介绍了Java中的IO流,包括字符与字节的概念、编码格式、File类的使用、IO流的分类和原理,以及通过代码示例展示了各种流的应用,如节点流、处理流、缓存流、转换流、对象流和随机访问文件流。同时,还探讨了IDEA中设置项目编码格式的方法,以及如何处理序列化和反序列化问题。
50 1
java基础:IO流 理论与代码示例(详解、idea设置统一utf-8编码问题)
|
19天前
|
算法 Java Linux
java制作海报四:java BufferedImage 转 InputStream 上传至OSS。png 图片合成到模板(另一个图片)上时,透明部分变成了黑色
这篇文章主要介绍了如何将Java中的BufferedImage对象转换为InputStream以上传至OSS,并解决了png图片合成时透明部分变黑的问题。
42 1
|
27天前
|
Java 数据处理 开发者
揭秘Java IO流:字节流与字符流的神秘面纱!
揭秘Java IO流:字节流与字符流的神秘面纱!
26 1
|
27天前
|
自然语言处理 Java 数据处理
Java IO流全解析:字节流和字符流的区别与联系!
Java IO流全解析:字节流和字符流的区别与联系!
56 1
|
2月前
|
安全 Java API
【Java面试题汇总】Java基础篇——String+集合+泛型+IO+异常+反射(2023版)
String常量池、String、StringBuffer、Stringbuilder有什么区别、List与Set的区别、ArrayList和LinkedList的区别、HashMap底层原理、ConcurrentHashMap、HashMap和Hashtable的区别、泛型擦除、ABA问题、IO多路复用、BIO、NIO、O、异常处理机制、反射
【Java面试题汇总】Java基础篇——String+集合+泛型+IO+异常+反射(2023版)
|
12天前
|
Java
Java 中 IO 流的分类详解
【10月更文挑战第10天】不同类型的 IO 流具有不同的特点和适用场景,我们可以根据具体的需求选择合适的流来进行数据的输入和输出操作。在实际应用中,还可以通过组合使用多种流来实现更复杂的功能。
30 0
|
2月前
|
Java 大数据 API
Java 流(Stream)、文件(File)和IO的区别
Java中的流(Stream)、文件(File)和输入/输出(I/O)是处理数据的关键概念。`File`类用于基本文件操作,如创建、删除和检查文件;流则提供了数据读写的抽象机制,适用于文件、内存和网络等多种数据源;I/O涵盖更广泛的输入输出操作,包括文件I/O、网络通信等,并支持异常处理和缓冲等功能。实际开发中,这三者常结合使用,以实现高效的数据处理。例如,`File`用于管理文件路径,`Stream`用于读写数据,I/O则处理复杂的输入输出需求。
|
25天前
|
存储 Java 程序员
【Java】文件IO
【Java】文件IO
33 0
|
2月前
|
数据采集 Java 数据挖掘
Java IO异常处理:在Web爬虫开发中的实践
Java IO异常处理:在Web爬虫开发中的实践