在Java程序中,通常会使用IO的输入输出,这里的输入输出是相对你的程序而言的。比如你写一个程序要读取一个文本文件,这里有两个对象,你的程序,还有就是文本文件。你的程序需要数据,那么用的应该是输入流(InputStream).
public class ReadText {
public static void main(String[] args){
try {
FileInputStream input = new FileInputStream("test.txt");
/*对于我接下来的程序,我要读取数据,但我完全不需要考虑数据从何
* 而来,我只要知道有个input对象,它给我了读取数据的方法、途径*/
int data;
while((data = input.read())!= -1){
System.out.print((char)data);
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
你可以把自己想象成站在海边,然后波涛汹涌的海水(数据)正像你涌来。下面是InputStream的源码:
public abstract class InputStream implements Closeable {
private static final int SKIP_BUFFER_SIZE = 2048;
private static byte[] skipBuffer;
/*
* 从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经
* 到达流末尾而没有可用的字节,则返回值-1。在输入数据可用、检测到流末尾或者抛出异
* 常前,此方法一直阻塞。 子类必须提供此方法的一个实现。
*/
public abstract int read() throws IOException;
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int c = read();
if (c == -1) {
return -1;
}
b[off] = (byte) c;
int i = 1;
try {
for (; i < len; i++) {
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte) c;
}
} catch (IOException ee) {
}
return i;
}
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
public long skip(long n) throws IOException {
long remaining = n;
int nr;
if (skipBuffer == null)
skipBuffer = new byte[SKIP_BUFFER_SIZE];
byte[] localSkipBuffer = skipBuffer;
if (n <= 0) {
return 0;
}
while (remaining > 0) {
nr = read(localSkipBuffer, 0,
(int) Math.min(SKIP_BUFFER_SIZE, remaining));
if (nr < 0) {
break;
}
remaining -= nr;
}
return n - remaining;
}
public int available() throws IOException {
return 0;
}
public void close() throws IOException {
}
public synchronized void mark(int readlimit) {
}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
public boolean markSupported() {
return false;
}
}