java中的inputstream是一个面向字节的流抽象类,其根据具体应用派生出各种具体的类。

比如FileInputStream就是继承于InputStream,专门用来读取文件流的对象,其具体继承结构如图

java中inputstream的使用_抽象类


我们发现,是从抽象类InputStream继承而来的。


我们继续看例子,实现从txt文件中,读取字符。其中test.txt已经提前新建好,放到工程目录下了。

package com.itbuluoge.test;

import java.io.FileInputStream;

public class ByteInputFile {

public static String read() throws Exception
{
FileInputStream fit=new FileInputStream("test.txt");
int c;
String sb="";
while((c=fit.read())!=-1)
{
sb+=(char)c;
}
return sb;
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.out.println(read());
}

}



输出结果

java中inputstream的使用_java_02



这里要注意一点,InputStream是面向字节的流,因此每次操作都是针对于一个字节,因此就无法对中文进行处理,读出写入都会出现乱码。继承而来的FileInputStream是一样的。因此我们这里测试,只是用了英文字符