/**
* 2018.11.4
* 作者:孟小鱼
* 内容:演示FileInputStream类的使用(将文件里的内容读入到内存当中)
*/
package com.io1;
import java.io.*;
public class iotest {
public static void main(String[] args) {
//得到一个文件对象:f->e:\\aa.txt
File f=new File("E:\\javademo\\Jiafaqi.java");
//字节输入流
FileInputStream fis=null;
//因为File没有读写操作,所以要借助InputStream
try {
fis=new FileInputStream(f);
//定义一个字节数组,相当于缓冲
byte []bytes=new byte[1024];
int n=0;//得到实际读取到的字节数
/**
*public int read(byte[] b)
throws IOException从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。在某些输入可用之前,此方法将阻塞。
覆盖:
类 InputStream 中的 read
参数:
b - 存储读取数据的缓冲区。
返回:
读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
抛出:
IOException - 如果发生 I/O 错误。
*/
//循环读取——-1的解释查API文档
while((n=fis.read(bytes))!=-1)
{
//把字节转换成String
String s=new String(bytes,0,n);
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}finally
{
//关闭文件流必须放在这而且要抛出异常
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}