1.InputStream类型
继承自InputStream的流都是用于向程序中输入数据,且数据的单位为字节(8bit);下图中深色为节点流,浅色为处理流。
2.InputStream的基本方法
InputStream的有以下几个的基本用法:
1) 读取一个字节并以整数的形式返回(0~255),如果返回-1已到输入流的末尾。
int read() throws IOException
2) 读取一系列字节并存储到一个数组buffer,返回实际读取的字节数,如果读取前已到输入的末尾返回-1.
int read(byte[] buffer) throws IOException
3) 读取length个字节,并存储一个字节数组buffer,从length位置开始,返回实际读取的字节数,如果读取前以到输入的末尾返回-1.
int read(byte[] buffer, int offset, int length) throws IOException
4) 关闭释放内存资源。
void close() throws IOException
5) 跳过n个字节不读,返回实际跳过的字节数。
long skip(long n) throws IOException
3.InputStream的例子
package com.owen.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 读取文件 FileInputStream
* @author OwenWilliam 2016-7-19
* @since
* @version v1.0.0
*
*/
public class TestFileInputStream
{
public static void main(String[] args)
{
int b = 0;
FileInputStream in = null;
try
{
in = new FileInputStream("E:\\workspace\\Java\\IO\\src\\com\\owen\\io\\TestFileInputStream.java");
}
catch (FileNotFoundException e)
{
System.out.println("找不到指定文件");
System.exit(-1);
}
try
{
long num = 0;
while ((b = in.read()) != -1)
{
System.out.print((char)b);
num++;
}
in.close();
System.out.println();
System.out.println("其读取了 " + num + " 个字节");
}
catch (IOException el)
{
System.out.println("文件读取错误");
System.exit(-1);
}
}
}