Java DataInputStream Class

Java 流(Stream)Java Stream (Stream)


Data input streams allow applications to read primitive Java data types from an underlying input stream in a machine-independent way.

The following constructor is used to create a data input stream object.

DataInputStream dis = new DataInputStream(InputStream in);

Another way to create it is to accept a byte array and two integer variables off and len, where off indicates the first byte to read and len indicates the length of bytes to read.

No. Method Description
1 public final int read(byte[] r, int off, int len)throws IOException
Reads from the contained input streamlenbytes into a byte array. If len is -1, returns the number of bytes read.
2 Public final int read(byte [] b)throws IOException
Reads a certain number of bytes from the contained input stream and stores them in the buffer arraybin.
3
  1. public final Boolean readBooolean()throws IOException,
  2. public final byte readByte()throws IOException,
  3. public final short readShort()throws IOException
  4. public final Int readInt()throws IOException
Reads bytes from the input stream and returns two bytes from the input stream as the corresponding primitive data type return value.
4 public String readLine() throws IOException
Reads the next line of text from the input stream.

Example

The following example demonstrates the use of DataInputStream and DataOutputStream. It reads 5 lines from the text file test.txt, converts them to uppercase letters, and finally saves them in another file test1.txt.

The content of the file test.tx is as follows:

example1
example2
example3
example4
example5

Example

import java.io.*; public class Test{ public static void main(String args[])throws IOException{ DataInputStream in = new DataInputStream(new FileInputStream("test.txt")); DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt")); BufferedReader d = new BufferedReader(new InputStreamReader(in)); String count; while((count = d.readLine()) != null){ String u = count.toUpperCase(); System.out.println(u); out.writeBytes(u + " ,"); } d.close(); out.close(); } }

The result of compiling and running the above example is as follows:

EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4
EXAMPLE5

Java 流(Stream)Java Stream (Stream)

Other Extensions