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

