Java IO Tutorial - Java ObjectOutputStream .writeUTF (String str)








Syntax

ObjectOutputStream.writeUTF(String str) has the following syntax.

public void writeUTF(String str)  throws IOException

Example

In the following code shows how to use ObjectOutputStream.writeUTF(String str) method.

//from w  ww . ja va  2 s.com
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.util.Calendar;

public class Main {
  public static void main(String[] args) throws Exception {

    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(
        new FileOutputStream("file.data")));

    out.writeObject(Calendar.getInstance());
    out.writeObject(new BigDecimal("123.123"));
    out.writeInt(1);
    out.writeUTF("tutorial");
    out.close();

    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(
        new FileInputStream("file.data")));

    BigDecimal price;
    int unit;
    String desc;

    Calendar date = (Calendar) in.readObject();
    System.out.println(date);
    
    price = (BigDecimal) in.readObject();
    unit = in.readInt();
    desc = in.readUTF();
    System.out.println(unit);
    System.out.println(desc);
    System.out.println(price);
    in.close();
  }
}

The code above generates the following result.