Walt
Walt

Reputation: 111

Writing array data to a binary file in Java

I'm trying to store the following arrays in binary, and read them back in after:

private int[10] number;
private String[10] name;
private int[10] age;

What is the best way to store them to a binary file, and read them back in afterwards? An example value for each array are:

number[0] = 1; name[0] = "Henry"; age[0] = 35;

So the data belongs sort of together.

Edit: Basically I want to store data from variables (arrays) using a binary text file, binary is a must, and then read the data back in. So in short I want to have a way to store data so when I close the application the data is not lost and can be retrieved each session.

Upvotes: 1

Views: 3141

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

You could write custom encoder and decoder e.g. by mapping String to byte[] with String.getBytes() and then writing each byte with OutputStream.write() method. The question is what do you mean by "the best way" because:

  1. Do you need to support different locales? What is the String locale as getBytes() uses platform's default charset.
  2. Do you need to compress the binary data to save space as String might be either very long or very short.
  3. Do you plan to share the binary files with other applications? If so it's best to use a format supported in few languages e.g. Google Protobuf.

If the files are ever to be read outside of your application then Protobuf seems like a sane choice. It would however be an overkill for a Hello World application.

The simpliest approach would be to use ObjectOutputStream and ObjectInputStream but it's far from pretty:

String fileName = "data.set";

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName))) {
  for (int n : number) {
    out.writeInt(n);
  }
  for (String n : name) {
    out.writeUTF(n);
  }
  for (int a : age) {
    out.writeInt(a);
  }
}

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName))) {
  for (int i = 0; i < number.length; i++) {
    number[i] = in.readInt();
  }
  for (int i = 0; i < name.length; i++) {
    name[i] = in.readUTF();
  }
  for (int i = 0; i < age.length; i++) {
    age[i] = in.readInt();
  }
}

Upvotes: 2

Related Questions