Reputation: 111
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
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:
String
locale as getBytes()
uses platform's default charset.String
might be either very long or very short.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