Java DataOutputStream write primitive types to file

Description

Java DataOutputStream write primitive types to file

import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String destFile = "Main.dat";

    try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(
        destFile))) {// w ww . j  a v a 2 s  .  c  o m

      // Write some primitive values and a string
      dos.writeInt(1234);
      dos.writeDouble(6789.50);
      dos.writeBoolean(true);
      dos.writeUTF("test from demo2s.com");

      // Flush the written data to the file
      dos.flush();

      System.out.println("Data saved");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related