Java IO Tutorial - Java ObjectOutputStream .writeInt (int val)








Syntax

ObjectOutputStream.writeInt(int val) has the following syntax.

public void writeInt(int val)  throws IOException

Example

In the following code shows how to use ObjectOutputStream.writeInt(int val) method.

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;
/*ww  w . j a v  a2  s. co m*/
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.