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-

猜你喜欢

转载自blog.csdn.net/dodod2012/article/details/80763015
int