Java.io.LineNumberInputStream.read() 方法



描述

java.io.LineNumberInputStream.read(byte[] b, int off, int len) 方法最多读取此输入流中的 len 个字节到字节数组中。此方法会阻塞,直到有输入可用。

声明

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

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

参数

  • b − 将数据读取到的缓冲区。

  • off − 数据的起始偏移量。

  • len − 读取的字节最大数量。

返回值

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

异常

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

示例

以下示例演示了 java.io.LineNumberInputStream.read(byte[] b, int off, int len) 方法的用法。

package com.tutorialspoint;

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

public class LineNumberInputStreamDemo {
   public static void main(String[] args) throws IOException {
      LineNumberInputStream lnis = null;
      FileInputStream fis = null;
      byte[] buf = new byte[5];
      int i;
      char c;
      
      try {
         // create new input stream
         fis = new FileInputStream("C:/test.txt");
         lnis = new LineNumberInputStream(fis);
         
         // read bytes to the buffer
         i = lnis.read(buf, 2, 3);
         System.out.println("The number of char read: "+i);
               
         // for each byte in buffer
         for(byte b:buf) {
         
            // if byte is zero
            if(b == 0)
               c = '-';
            else
               c = (char)b;
      
            // print char
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      } finally {
         // closes the stream and releases any system resources
         if(fis!=null)
            fis.close();
         if(lnis!=null)
            lnis.close();      
      }
   }
}

假设我们有一个文本文件 c:/test.txt,其内容如下。此文件将用作我们示例程序的输入:

ABCDE

让我们编译并运行上述程序,这将产生以下结果:

The number of char read: 3
--ABC
java_io_linenumberinputstream.htm
广告
© . All rights reserved.