例子
下面的示例显示java.io.LineNumberInputStream.read(byte [] b,int off,int len)方法的用法。
package com.jc2182;
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 ,其内容如下。该文件将用作示例程序的输入-
让我们编译并运行以上程序,这将产生以下结果-
The number of char read: 3
--ABC