InputStream:
字节输入流的超类.
1.read():读取一个字节并返回,没有字节返回-1
2.read(byte[] b):读取一定量的字节数,并存储到字节数组中,返回读取到的字节数
用于读取文件的字节输入流对象,FileInputStream()
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
File file = new File("tempfile/file.txt");
//创建一个字节流输入对象
FileInputStream fis = new FileInputStream(file);
//读取数据
/*
第一种读取文件方法
*/
//1.1
// int read1 = fis.read();//读取下一个字节
// System.out.println("ch1="+read1);
// int read2 = fis.read();//读取下一个字节
// System.out.println("ch1="+read2);
//1.2
// int ch = 0;
// while((ch = fis.read()) != -1){ //循环n次
// System.out.println("ch="+(char)ch);
// }
//最后会有文件结束标识
/*
第二种读取方法
*/
byte[] buf = new byte[4096];//长度可以定义为1024的整数倍
//2.1
int len = 0;
while((len = fis.read(buf))!= -1){ //循环n/1024次
System.out.println(new String(buf,0,len));
}
//2.2
// int len1 = fis.read(buf);//从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中。返回读取到的数量
// System.out.println(len1+":"+new String(buf,0,len1));//String的构造方法,用这种方法保证安全性
// int len2 = fis.read(buf);//从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中。返回读取到的数量
// System.out.println(len2+":"+new String(buf,0,len2));
fis.close();
}
}
来源:https://blog.csdn.net/weixin_42735725/article/details/102755659