例子
下面的示例演示java.io.DataInputStream.read(byte [] b,int off,int len)方法的用法。
package com.jc2182;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class DataInputStreamDemo {
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
try {
// create input stream from file input stream
is = new FileInputStream("c:\\test.txt");
// create data input stream
dis = new DataInputStream(is);
// count the available bytes form the input stream
int count = is.available();
// create buffer
byte[] bs = new byte[count];
// read len data into buffer starting at off
dis.read(bs, 4, 3);
// for each byte in the buffer
for (byte b:bs) {
// convert byte into character
char c = (char)b;
// empty byte as char '0'
if(b == 0)
c = '0';
// print the character
System.out.print(c);
}
} catch(Exception e) {
// if any I/O error occurs
e.printStackTrace();
} finally {
// releases any associated system files with this stream
if(is!=null)
is.close();
if(dis!=null)
dis.close();
}
}
}
假设我们有一个文本文件c:/test.txt ,其内容如下。该文件将用作示例程序的输入-
让我们编译并运行以上程序,这将产生以下结果-