文件输入流(FileInputStream)

news.txt = hello everyone

news01.txt = everyonebuddy,hellohi 

package file.InputStream_;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStream_ {
    public static void main(String[] args) {

    }
    /*
    *这样单字符读取太慢,利用数组会比较快
    */
    @Test
    public void readFile01() throws IOException {
        String filepath = "d:\\news.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {//创建FileInputStream,用于读取d:\news.txt文件
             fileInputStream = new FileInputStream(filepath);
            //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
            //如果返回-1,表示读取完毕
            while((readData = fileInputStream.read()) != -1){
                System.out.print((char)readData);//转成字符显示
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {//关闭文件流,释放资源
            fileInputStream.close();
        }
    }
    @Test
    public void readFile02() throws IOException {
        String filepath = "d:\\news01.txt";
        byte[] buff = new byte[8];//一次取8个字节
        int readlen = 0;
        FileInputStream fileInputStream = null;
        try {//创建FileInputStream,用于读取d:\news.txt文件
            fileInputStream = new FileInputStream(filepath);
            //从该输入流读取最多b.length字节的数据到字节数组,此方法将阻塞,
            //如果返回-1,表示读取完毕
            while((readlen = fileInputStream.read(buff)) != -1){
                System.out.print(new String(buff,0,readlen));//打印buff数组,索引从0开始打印,每次最多打印8个字符
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {//关闭文件流,释放资源
            fileInputStream.close();
        }
    }
}

输出1:

输出2:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值