📌  相关文章
📜  Java I/O-DataInputStream

📅  最后修改于: 2020-09-27 02:38:18             🧑  作者: Mango

Java DataInputStream类

Java DataInputStream类允许应用程序以独立于机器的方式从输入流中读取原始数据。

Java应用程序通常使用数据输出流来写入数据,以后可以由数据输入流读取。

Java DataInputStream类声明

让我们看一下java.io.DataInputStream类的声明:

public class DataInputStream extends FilterInputStream implements DataInput

Java DataInputStream类方法

Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read a string that has been encoded using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into the buffer array.
void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.

DataInputStream类的示例

在此示例中,我们正在从文件testout.txt文件中读取数据。

package com.javatpoint;
import java.io.*;  
public class DataStreamExample {
  public static void main(String[] args) throws IOException {
    InputStream input = new FileInputStream("D:\\testout.txt");
    DataInputStream inst = new DataInputStream(input);
    int count = input.available();
    byte[] ary = new byte[count];
    inst.read(ary);
    for (byte bt : ary) {
      char k = (char) bt;
      System.out.print(k+"-");
    }
  }
}

在这里,我们假设您在“ testout.txt”文件中包含以下数据:

JAVA

输出:

J-A-V-A