InputStream——FileInputStream使用示例

本文介绍了使用Java进行文件读取的不同方法,包括根据文件大小定义字节数组、逐字节读取及未知文件大小时的处理策略。

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

第一个构造方法

public FileInputStream(File file)throws FileNotFoundException


public class Test12 {
     public static void main(String[] args) throws IOException {
         File f = new File("d:" + File.separator+"test.txt");
         InputStream in=new FileInputStream(f);
         byte[] b=new byte[1024];
         int len=in.read(b);
        in.close();
         System.out.println(new String(b,0,len));
     }
 }

但以上方法是有问题的,用不用开辟这么大的一个字节数组,明显是浪费嘛,我们可以根据文件的大小来定义字节数组的大小,File类中的方法:public long length()

public class Test13 {
     public static void main(String[] args) throws IOException {
         File f = new File("d:" + File.separator+"test.txt");
         InputStream in=new FileInputStream(f);
        byte[] b=new byte[(int) f.length()];
         in.read(b);
         in.close();
         System.out.println(new String(b));
     }
 }

我们换种方式,一个字节一个字节读入~

 public class Test14 {
     public static void main(String[] args) throws IOException {
         File f = new File("d:" + File.separator+"test.txt");
        InputStream in=new FileInputStream(f);
         byte[] b=new byte[(int) f.length()];
         for(int i=0;i<b.length;i++){
            b[i]=(byte) in.read();
        }
        in.close();
        System.out.println(new String(b));
     }
}

但以上情况只适合知道输入文件的大小,不知道的话用如下方法:

public class Test15 {
    public static void main(String[] args) throws IOException {
         File f = new File("d:" + File.separator+"test.txt");
        InputStream in=new FileInputStream(f);
        byte[] b=new byte[1024];
        int temp=0;
        int len=0;
        while((temp=in.read())!=-1){//-1为文件读完的标志
             b[len]=(byte) temp;
            len++;
         }
         in.close();
        System.out.println(new String(b,0,len));
     }
 }



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值