一.InputStream类介绍
JDK API文档描述:
此抽象类是表示字节输入流的所有类的超类
作用:读取文件,每次只读取一个字节(OutputStream每次只输出一个字节)
二.InputStream类中常用的方法
由于InputStream是一个抽象类,我们不能直接创建其对象,但它的子类会重写它其中的方法,下面使用其子类FileInputStream来演示其中的方法
FileInputStream的构造方法:
c盘下测试文件的信息:
测试类:
package com.xiao.InputStream; import org.junit.Test; import java.io.FileInputStream; /** * @Author 笑笑 * @Date 18:01 2018/05/05 */ public class InputStreamDemo { // int read() 从此输入流中读取一个数据字节。 @Test public void test_01() throws Exception{ //使用构造方法指定要读取的数据源 FileInputStream fis = new FileInputStream("c:\\1.txt"); //读取一个字节,每调用一次,会自动读取下一个字节,如果已到达文件末尾,返回-1 int read = fis.read(); //结果为97(小写字母a对应的ASCII码值) System.out.println(read); fis.close(); } //使用循环方式读取 @Test public void test_02() throws Exception{ //使用构造方法指定要读取的数据源 FileInputStream fis = new FileInputStream("c:\\1.txt"); int len = 0; while((len=fis.read()) != -1){ //强制转换为字符类型输出 System.out.print((char) len); } fis.close(); } //int read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。数组作为缓冲的作用 @Test public void test_03() throws Exception{ //使用构造方法指定要读取的数据源 FileInputStream fis = new FileInputStream("c:\\1.txt"); //创建字节数组 byte[] b = new byte[2]; int read = fis.read(b); //结果为ab(使用String类的构造方法把字节数组转换成了字符串) System.out.println(new String(b)); fis.close(); } //循环读取 @Test public void test_04() throws Exception{ //使用构造方法指定要读取的数据源 FileInputStream fis = new FileInputStream("c:\\1.txt"); //创建字节数组, byte[] b = new byte[2]; int len = 0; while ((len = fis.read(b)) != -1){ System.out.print(new String(b,0,len)); } fis.close(); } }