How do I use DataInputStream and DataOutputStream?

DataOutputStream and DataInputStream give us the power to write and read primitive data type to a media such as file. Both of this class have the corresponding method to write primitive data and read it back.

Using this class make it easier to read integer, float, double data and others without needing to interpret if the read data should be an integer or a float data. Let’s see our code below.

The generated result of our program are:

  • Bhavani

    In which path “cities.dat” will be created

    • Wayan Saryada

      Hi Bhavani,

      The output file, cities.dat, will be create in the path where you executed the example code. You can also change the constructor call in FileOutputStream above with a complete path where you want to save the output. Or instead of using string, you can also pass an instance of with a complete path and filename to FileOutputStream.