InputStream不可以读取文件,它是一个Abstract的类,根本不可能实例化,是所有输入流的基类。而FileInputStream是InputStream的一个实现类,用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。
以下是一个例子
package com.io.Stream;
//InputStream 的基本用法:
//读取一个字节并以证书的形式返回(0~255) 如果返回-1已到输入流的结尾。int read()throws IoException
//读取一系列字节并存储到一个数组buffer,返回实际读取的字节数,如果读取前已到输入流的末尾返回-1 int read(byte[]buffer)throws IoException
//读取length个字节 并存储到一个字节数组buffer,从length位置开始返回实际读取的字节数,如果读取前以到输入流的末尾返回-1 int read(byte[] buffer,int offset,int length)throws IoException
//关闭释放内存资源 void close()throws IoException
//跳过n个字节不读,返回实际跳过的字节数 long skip(long n)throws IoException
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.stream.FileCacheImageInputStream;
public class InputStream {
public static void main(String[] args) {
FileInputStream files=null;
int b = 0;
try{
files=new FileInputStream("F:/bb/ii/tt.txt");
}catch(FileNotFoundException e){
System.out.println("系统文件不存在");
System.exit(-1);
}
try{
long num=0;
while((b= files.read())!=-1){
System.out.print((char)b);
num++;
}
files.close();
System.out.println();
System.out.println("读取成功");
System.out.println("共读取了"+num+"个字节");
}catch(IOException e){
System.out.println("此文件读取出错");
System.exit(-1);
}
}
}