Java.io.FileInputStream.read() 方法



描述

java.io.FileInputStream.read(byte[] b) 方法最多读取此文件输入流中 b.length 个字节到字节数组中。该方法会阻塞,直到有输入可用。

声明

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

public int read(byte[] b)

参数

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

返回值

该方法返回读取到缓冲区中的字节总数,如果没有任何更多数据可读,则返回 -1。

异常

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

示例

以下示例演示了 java.io.FileInputStream.read(byte[] b) 方法的使用。

package com.tutorialspoint;

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);
         
         // 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;
            
            // 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: 4
Bytes read: ABCD
java_io_fileinputstream.htm
广告

© . All rights reserved.