DataOutputStream and DataInputStream: write and read primitive data type to a file : DataOutputStream « File Input Output « Java






DataOutputStream and DataInputStream: write and read primitive data type to a file

  

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Main {

  public static void main(String[] args) throws Exception{
    int idA = 1;
    String nameA = "City";
    int populationA = 5;
    float tempA = 1.0f;

    int idB = 2;
    String nameB = "S";
    int populationB = 2;
    float tempB = 1.45f;

    FileOutputStream fos = new FileOutputStream("cities.dat");
    DataOutputStream dos = new DataOutputStream(fos);

    dos.writeInt(idA);
    dos.writeUTF(nameA);
    dos.writeInt(populationA);
    dos.writeFloat(tempA);

    dos.writeInt(idB);
    dos.writeUTF(nameB);
    dos.writeInt(populationB);
    dos.writeFloat(tempB);

    dos.flush();
    dos.close();

    FileInputStream fis = new FileInputStream("cities.dat");
    DataInputStream dis = new DataInputStream(fis);

    int cityId = dis.readInt();
    System.out.println("City Id: " + cityId);
    String cityName = dis.readUTF();
    System.out.println("City Name: " + cityName);
    int cityPopulation = dis.readInt();
    System.out.println("City Population: " + cityPopulation);
    float cityTemperature = dis.readFloat();
    System.out.println("City Temperature: " + cityTemperature);
  }
}

   
    
  








Related examples in the same category

1.DataInputStream out of FileInputStream, DataOutputStream out of FileOutputStream
2.new DataOutputStream(new BufferedOutputStream(new FileOutputStream()))
3.Create DataOutputStream from FileOutputStream and Write various types of data
4.Write short type value with DataOutputStream
5.Write different data types with DataOutputStream
6.Determine number of bytes written to DataOutputStream
7.Flush output stream
8.Write boolean to a file using DataOutputStream
9.Write byte to a file using DataOutputStream
10.Write char to a file using DataOutputStream
11.Write double to a file using DataOutputStream
12.Write float to a file using DataOutputStream
13.Write int to a file using DataOutputStream
14.Write long to a file using DataOutputStream
15.Write short to a file using DataOutputStream
16.Write String as bytes to a file using DataOutputStream
17.Write String as characters to a file using DataOutputStream
18.DataInputStream, DataOutputStream
19.Provide a debug trace of the stuff thats being written out into the DataOutputStream