FileInputStream 读取文件内容

public class Test {
    public static void main(String[] args) throws IOException {
        final String path = "D:/1.txt";
	//1、得到数据文件
	File file = new File(path); 
	//2、建立数据通道
	FileInputStream fileInputStream = new FileInputStream(file);   
	byte[] buf = new byte[1024];  
	int length = 0;
	//循环读取文件内容,输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
	//当文件读取到结尾时返回 -1,循环结束。
	while((length = fileInputStream.read(buf)) != -1){   
	    System.out.print(new String(buf,0,length));
	}
	//最后记得,关闭流
	fileInputStream.close();
    }
}

读取结果:



FileInputStream类的其他常用方法:

注:以下代码的输出均以上面的1.txt文件为例。

1、available()  

返回类型: int

作用:返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。即输入流中当前的字节数。

System.out.println(fileInputStream.available());

输出:10 

2、skip(long n)

返回类型:long

作用:从输入流中跳过并丢弃n个字节的数据

System.out.println(fileInputStream.skip(4));

输出:4

跳过前面4个字节,所以读取到的数据为: ,世界(一个汉字等于两个字节)


3、read()

返回类型:int

作用:从输入流中读取一个数据字节

System.out.println(fileInputStream.read());

输出:196

4、read(byte[] b,int off,int len)

返回类型:int

作用:从输入流中读取len个字节的数据到byte数组中,数据存放在byte数组中从off开始后的len个空间内。

System.out.println(fileInputStream.read(buf,3,4));
System.out.println(new String(buf,0,7));

输出: 从输入流中读取4个字节数据,存放到buf数组的 3,4,5,6个空间里,所以在输出的时候,buf前3个空间为空,输出□,后面4个空间输出对应的值:你好。

猜你喜欢

转载自blog.csdn.net/qq_37618797/article/details/81011896