简体   繁体   中英

How to get a particular instance of serialized object from file?

Suppose, I have made a class named Worker.

public class Worker implements Serializable{
    String username, password;
} 

And say, in the main function/any other method that works with this class, I created few instances.

Worker first = new Worker("Arty", "Sif");  //Worker(String name, String pass)
Worker second = new Worker("Sirius", "Pass");

And then I stored them in a file, for example "store.bin" using objectoutputstream. My question is, if I want a particular instance during runtime, Sirius for example, is there any OTHER way to get it than just reading through the entire file loading each object and comparing them with a unique field of the instance? As doing so will take a lot of time. Thanks in advance.

Well, there are already designed tools for that and they are databases. They do exactly what you described.

There's even one called SQLite, which does even the implementation as you described, storing data as a binary file, say sqlite.db .

What you seem to be doing is read the file every time someone asks for a specific worker; you shouldn't need to do that. Just read the file once and put all results in a Map .

class PasswordLoader {
  Map<String, String> users = new HashMap<>();
  public WorkerManager(String filename) {
    List<Worker> all = readFromFile(filename);
    for (Worker worker : all) {
      users.put(worker.getName(), worker.getPassword());
    }
  }

  public String getPasswordForUsername(String username) {
    return users.get(username);
  }
}

It does have several issues; for example, if new Workers get added, the file will be updated but the map won't. It's best to route all Worker management (adding, removing, querying, etc) through this class so it can stay up to date. Another advantage of doing it this way is that if you want to change how the data is stored later (eg. using a database), you only need to change this one class because it's the only one in contact with how the Workers are stored.

Also, passwords should never be stored as String s; that's a security issue due to how Strings are stored in Java; it may linger in memory even after you're done using it.

As I wrote in my comment, it's not a good idea to use Java Serialization either, but since you've got that down, pressed for time and it's not a production project, I guess it'll do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM