Java I/O How to - Write int array to a file








Question

We would like to know how to write int array to a file.

Answer

// ww  w.  ja v a 2  s.c o  m
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] arguments) {
    int[] data = { 137, 89, 82, 181, 50, 220, 103, 20, 0, 59 };
    try {
      FileOutputStream file = new FileOutputStream("pic.dat");
      for (int i = 0; i < data.length; i++)
        file.write(data[i]);
      file.close();
    } catch (IOException e) {
      System.out.println("Error - " + e.toString());
    }
  }
}