简体   繁体   中英

Java: check if object exists in object file before writing

I have a file called "objects.txt" which contains some serializable objects.

I want to write some objects to the file.

Is there a way to check if the objects I want to write to the file already exist in the file before writing? Would it be better to not check even if the objects already exist in the file?

Below is example of writing object to file:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.swing.JFrame;

public class WriteObjectsDemo {

    public static void main(String[] args)
    {
        try(FileOutputStream f = new FileOutputStream("objects.txt"))
        {
            ObjectOutputStream o = new ObjectOutputStream(f);
            // Write objects to file
            JFrame j = new JFrame();
            o.writeObject(j);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

}

I'd say the answer is maybe . It might be pushing the serialization machinery beyond its comfort zone, but if it's going to work at all it'll go something like this:

First, read through the file once using a FileInputStream wrapped in an ObjectInputStream in order to determine whether or not the file already contains your object. Close the stream when you're done.

Then, if you decide you want to write your object, open the file for appending with new FileOutputStream(file, true) , wrap that stream in an ObjectOutputStream and write away.

PS: I'd suggest reconsidering the .txt extension on your filename. The serialized object data is most definitely not text.

Is there a way to check if the objects I want to write to the file already exist in the file before writing?

Yes.

Read the entire file, deserialize every object in it, and see if the object you're about to write is already there.

Not very efficient, is it?

So one better way:

  1. When your process starts, read all the objects in the file into a Set<> .
  2. While you're processing, add objects to that Set<> . Since a Set<> only allows a single instance of any object, duplicate objects will be dropped.
  3. When you're done processing, rewrite the entire file from your Set<> , serializing every object in it to the file.

Note that to implement this, your objects need to properly override the equals() method and the hashCode() method so equivalent objects compare as equals. See Compare two objects with .equals() and == operator to start - and read the accepted answer - all of it. Then read the links. Then think hard about what equals() means for your objects. Then implement equals() and hashCode() methods in your Java code that work .

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