java.io.FileInputStream.read(byte[] b, int off, int len)方法实例

原文地址:https://www.yiibai.com/java/io/fileinputstream_read_byte_len.html

java.io.FileInputStream.read(byte[] b, int off, int len) 读取从此输入流中的数据len个字节到字节数组,开始在目标数组b的偏移。

声明

以下是方法java.io.FileInputStream.read(byte[] b, int off, int len)的声明:

public int read(byte[] b, int off, int len)

参数

  • b - 读取字节数组数据。

  • off - 开始在目标数组b的偏移。

  • len - 要读取的最大字节数。

返回值

该方法返回读入缓冲区的字节总数

异常

  • IOException - 如果发生I/ O错误。

  • NullPointerException - 如果b为 null.

  • IndexOutOfBoundsException - 如果len或off是负数的,或 b.length-off大于b.length。

例子

下面的例子显示java.io.FileInputStream.read(byte[] b, int off, int len)方法的用法。

package com.yiibai;

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

public class FileInputStreamDemo {
   public static void main(String[] args) throws IOException {
      
      FileInputStream fis = null;
      int i = 0;
      char c;
      byte[] bs = new byte[4];
      
      try{
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // read bytes to the buffer
         i=fis.read(bs, 2, 1);
         
         // prints
         System.out.println("Number of bytes read: "+i);
         System.out.print("Bytes read: ");
         
         // for each byte in buffer
         for(byte b:bs)
         {
            // converts byte to character
            c=(char)b;
            if(b==0)
               c='-';
            
            // print
            System.out.print(c);
         }   
      }catch(Exception ex){
         // if any error occurs
         ex.printStackTrace();
      }finally{
         
         // releases all system resources from the streams
         if(fis!=null)
            fis.close();
      }
   }
}

假设我们有一个文本文件c:/ test.txt,它具有以下内容。该文件将被用作输入到我们的示例程序:

ABCDEF

让我们来编译和运行上面的程序,这将产生以下结果:

Number of bytes read: 1
Bytes read: --A-

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值