Java I/O How to - Write double/UTF to a file








Question

We would like to know how to write double/UTF to a file.

Answer

//w w w  .ja  v a  2s.  co m
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainClass {
  public static void main(String[] args) throws IOException {
    DataOutputStream out2 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
        "Data.txt")));
    out2.writeDouble(3.14159);
    out2.writeUTF("Square root of 2");
    out2.close();

    DataInputStream in5 = new DataInputStream(new BufferedInputStream(new FileInputStream(
        "Data.txt")));

    System.out.println(in5.readDouble());
    System.out.println(in5.readUTF());
  }
}

The code above generates the following result.