Data Types Read Write Java

Data Types Read Write Java


DataInputStream includes many methods like readByte(), readInt(), readLong(), readFloat(), readDouble() and readUTF() etc with which a byte, an integer, a long, a float, a double and a word can be read as a whole. Similarly, the DataOutputStream includes the methods like writeByte(), writeInt(), writeLong(), writeFloat(), writeDouble() and writeUTF() that can write a byte, an integer, a long, a float, a double and a word at a time. In the following program, these methods are used.

Two programs exist – WriteDataTypes.java that writes to the file EveryThing.txt and ReadDataTypes.java that reads the values from the file and print them.

Data Types Read Write Java: The following program writes data types like int, double, long etc. into the file "EveryThing.txt".

The writeXXX() methods write the appropriate data type to the file, EveryThing.txt. The above two streams can be replaced as follows using anonymous objects that saves memory.

DataOutputStream dos = new DataOutputStream(new FileOutputStream("EveryThing.txt"));

The data written by writeXXX() methods in EveryThing.txt is not in a readable format (you can open and see how the file contents look). It must be read by readXXX() methods of DataInputStream as in the next program.

Following program reads data types from the file "”"EveryThing.txt"”" (written earlier in the previous program).

Data Types Read Write Java: The following program reads the data and prints at the DOS prompt.

Data Types Read Write Java
Output screen on Data Types Read Write Java

The readXXX() methods read the appropriate data type from the file and prints them. The two streams can be replaced as follows using anonymous objects to save memeory.

DataInputStream dis = new DataInputStream(new FileInputStream("EveryThing.txt"));

Leave a Reply

Your email address will not be published. Required fields are marked *