FileInputStream的两种读入方式

本文档展示了如何使用Java的FileInputStream进行文件操作,包括低效率的逐字节读取和高效率的按块读取。通过`m1`方法演示了字符流读取,而`m2`方法则重点讲解了使用byte数组提高读取性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package Inputstream;

import org.omg.CORBA.PUBLIC_MEMBER;
import org.testng.annotations.Test;

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

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

    }
@Test
    //这个方法是使用最低效率(一个字节一个字节读入)的方法
    public void m1() throws IOException {
        int b = 0;
        FileInputStream fileInputStream = new FileInputStream("D:\\学习\\Java学习\\IO\\new2.txt");
        try {
            while ((b=fileInputStream.read())!=-1){
                System.out.print((char)b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fileInputStream.close();
        }
    }
    @Test
    //这个方法是最常用的高效率(一次读入自定义大小的byte数组个字节)的方法
    public void m2() throws IOException {
        int b =0;
        //自定义一个大小为1024字节的数组
        byte[] but = new byte[1024];
        FileInputStream fileInputStream = new FileInputStream("D:\\学习\\Java学习\\IO\\new2.txt");

        try {
            //fileInputStream.read(but)的返回值是读取到的数据的字节数
            while((b = fileInputStream.read(but))!=-1){
                //将but字节数组中的数据转换成一个字符串输出
                System.out.println(new String(but,0,b));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fileInputStream.close();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值