DataInputStream类用于在DataOutputStream类的上下文中,可用于读取原始数据。
以下是创建DataInputStream的构造函数 -
InputStream in = new DataInputStream(InputStream in);
当创建了DataInputStream对象,就可以使用一些它的辅助方法来读取流或在流上执行其他操作。
| 编号 | 方法 | 描述 |
|---|---|---|
| 1 | public final int read(byte[] r, int off, int len)throws IOException |
将输入流中最多len个字节的数据读入一个字节数组。 返回读入缓冲区的总字节数,否则返回-1(如果它是文件末尾)。 |
| 2 | public final int read(byte [] b)throws IOException |
从输入流中读取一些字节并存储到字节数组中。 返回读入缓冲区的总字节数,否则返回-1(如果它是文件末尾)。 |
| 3 | public final Boolean readBooolean()throws IOException,public final byte readByte()throws IOException,public final short readShort()throws IOException,public final Int readInt()throws IOException |
这些方法将从包含InputStream中读取字节。返回InputStream后两个字节作为指定原始类型。 |
| 4 | public String readLine() throws IOException |
从输入流中读取下一行文本。 它读取连续的字节,将每个字节分别转换为字符,直到它遇到行终止符或文件结尾; 然后读取的字符作为String返回。 |
示例
以下是演示如何使用DataInputStream和DataOutputStream的示例。 此示例将字符串写入指定文件中,然后再从文件test.txt中读取内容,参考以下示例代码 -
import java.io.*;
public class DataInput_Stream {
public static void main(String args[]) throws IOException {
// 使用 UTF-8 编码将字符串写入到文件中
DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
dataOut.writeUTF("hello\n");
dataOut.writeUTF("yiibai\n");
// 从指定文件中读取内容
DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));
while (dataIn.available() > 0) {
String str = dataIn.readUTF();
System.out.print(str);
}
}
}
执行上面示例代码,得到以下结果 -
hello
yiibai
加公众号啦,蝴蝶的技术学习公众号
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。