Java DataInputStream Class
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 stream lenbytes 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 array bin. |
| 3 |
|
| 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
Other Extensions
Java Stream (Stream)