Java DataInputStream class
A data input stream lets an application machine-independent way to read primitive Java data types from an underlying input stream.
The following constructor is used to create a data input stream object.
DataInputStream dis = DataInputStream(InputStream in);
Another way to create is to receive a byte array, and two integer variable off, len, off represents the first byte read, len indicates the length of bytes read.
No. | Method Description |
---|---|
1 | public final int read (byte [] r, int off, int len) throws IOException Input stream contains from len bytes read into a byte array. If len is -1, it returns the number of bytes read. |
2 | Public final int read (byte [] b) throws IOException Read some number of bytes from the input stream contains and stores them into the buffer array b in. |
3 |
|
4 | public String readLine () throws IOException Reads the next line of text from the input stream. |
Examples
The following example illustrates the DataInputStream and DataOutputStream use this example to read from a text file test.txt 5 lines in and converted to uppercase letters, the last saved in another file test1.txt in.
import java.io.*; public class Test{ public static void main(String args[])throws IOException{ DataInputStream d = new DataInputStream(new FileInputStream("test.txt")); DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt")); String count; while((count = d.readLine()) != null){ String u = count.toUpperCase(); System.out.println(u); out.writeBytes(u + " ,"); } d.close(); out.close(); } }
The above examples compiled results are as follows:
THIS IS TEST 1 , THIS IS TEST 2 , THIS IS TEST 3 , THIS IS TEST 4 , THIS IS TEST 5 ,