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






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);
  }
}








11.18.DataOutputStream
11.18.1.Create DataOutputStream from ByteArrayOutputStream
11.18.2.Create DataOutputStream from BufferedOutputStream
11.18.3.Determine number of bytes written to DataOutputStream
11.18.4.Flush output stream
11.18.5.DataOutputStream and DataInputStream: write and read primitive data type to a file
11.18.6.Write integers using DataOutputStream
11.18.7.Write boolean to a file using DataOutputStream
11.18.8.Write byte to a file using DataOutputStream
11.18.9.Write char to a file using DataOutputStream
11.18.10.Write float to a file using DataOutputStream
11.18.11.Write long to a file using DataOutputStream
11.18.12.Write short to a file using DataOutputStream
11.18.13.Write String as bytes to a file using DataOutputStream
11.18.14.Write String as characters to a file using DataOutputStream
11.18.15.Write int to a file using DataOutputStream
11.18.16.Write double and UTF string using DataOutputStream with BufferedOutputStream backended