目录

DataInputStream

DataInputStream用于DataOutputStream的上下文中,可用于读取基元。

以下是创建InputStream的构造函数 -

InputStream in = new DataInputStream(InputStream in);

一旦掌握了DataInputStream对象,就会有一个辅助方法列表,可用于读取流或对流进行其他操作。

Sr.No. 方法和描述
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

(a) public final Boolean readBooolean()throws IOException

(b) public final byte readByte()throws IOException

(c) public final short readShort()throws IOException

(d) public final Int readInt()throws IOException

这些方法将从包含的InputStream中读取字节。 返回InputStream的后两个字节作为特定原始类型(Primitive)。

4

public String readLine() throws IOException

从输入流中读取下一行文本。 它读取连续的字节,将每个字节分别转换为字符,直到它遇到行终止符或文件结尾; 读取的字符然后作为String返回。

例子 (Example)

以下是演示DataInputStream和DataOutputStream的示例。 此示例读取文件test.txt中给出的5行,并将这些行转换为大写字母,最后将它们复制到另一个文件test1.txt中。

import java.io.*;
public class DataInput_Stream {
   public static void main(String args[])throws IOException {
      // writing string to a file encoded as modified UTF-8
      DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
      dataOut.writeUTF("hello");
      // Reading data from the same file
      DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));
      while(dataIn.available()>0) {
         String k = dataIn.readUTF();
         System.out.print(k+" ");
      }
   }
}

以下是上述计划的样本运行 -

输出 (Output)

hello
↑回到顶部↑
WIKI教程 @2018