I have a binary file, created in a Java program. The binary file contains an array of User objects.
It was created like this:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
User[] arrayOfUsers = new User[50];
for (int i = 0; i < 50; i++){
arrayOfUsers[i] = new User("Mr. ", i + "owitz");
}
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users.dat"));
oos.writeObject(arrayOfUsers);
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is the User
class:
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String firstname;
private String lastname;
public User(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
As of now, I only know how to read in the entire array at once. However, I typically only need to retrieve one or two User
objects from the array and I know their positions.
Is there any way to read just the index I want to read, without reading in everything?