Java - Primitive Data Type Write

Description

Primitive Data Type Write

Demo

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 = "primitives.dat";

    try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(
        destFile))) {/*from  w w w . ja  va 2 s .c om*/

      // Write some primitive values and a string
      dos.writeInt(1234);
      dos.writeDouble(6789.50);
      dos.writeBoolean(true);
      dos.writeUTF("Java Input/Output is cool!");

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

      System.out.println("Data has been written to "
          + (new File(destFile)).getAbsolutePath());
    } catch (FileNotFoundException e) {
      FileUtil.printFileNotFoundMsg(destFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

class FileUtil {
  // Prints the location details of a file
  public static void printFileNotFoundMsg(String fileName) {
    String workingDir = System.getProperty("user.dir");
    System.out.println("Could not find the file '" + fileName + "' in '"
        + workingDir + "' directory ");
  }

  // Closes a Closeable resource such as an input/output stream
  public static void close(Closeable resource) {
    if (resource != null) {
      try {
        resource.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

Result