简体   繁体   中英

Reading bytes from a deserialized file

I'm learning Java serialization following this tutorial . I have successfully read and used my object from a serialized file with the following code (imports omitted):

public class SimpleSerializationTest {
static class Person implements Serializable{
    String name;
    int age;
    boolean isMale;

    static final long serialVersionUID = 314L;
}

public static void main(String[] args) throws Exception{
    Person p = new Person();
    p.name = "Mark";
    p.age = 20;
    p.isMale = true;

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("mark.ser"));

    try{
        oos.writeObject(p);
    } catch(IOException ioe){
        ioe.printStackTrace();
    } finally{
        oos.close();
    }

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("mark.ser"));

    try{
        // NOTE: Will change this later!
        Person mark = (Person) ois.readObject();
        System.out.println(mark.name);
    } catch(IOException ioe){
        ioe.printStackTrace();
    } finally{
        ois.close();
    }
}
}

However, my main purpose in serializing an object is so that I can push it to a Redis store. So, for that, I don't need them in Object form but in byte form. So I change the contents of the final try-block to something like...

while(true){
   try{
        System.out.println(ois.readByte());
    } catch(EOFException eofe){
        eofe.printStackTrace();
        break;
    }
}

But this promptly throws an EOFException. Is there anything I'm doing wrong?

The Object Stream is tagged. This means if you read a different type of information to the one it expects it can get confused resulting in an EOFException rather than something more meaningful like IllegalStateException with an appropriate error message.

If you want the bytes which are written by an ObjectOutputStream the simplest thing to do is to use memory only.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream ois = new ObjectOutputStream(baos);
ois.writeObject(object);
ois.close();
byte[] bytes = baos.toByteArray();

If you want to push the instance into redis, you are able to use JRedis .

Sample code from documents .

// instance it
SimpleBean obj = new SimpleBean ("bean #" + i);

// get the next available object id from our Redis counter using INCR command
int id = redis.incr("SimpleBean::next_id")

// we can bind it a unique key using map (Redis "String") semantics now
String key = "objects::SimpleBean::" + id;

// voila: java object db
redis.set(key, obj);

// and lets add it to this set too since this is so much fun
redis.sadd("object_set", obj);

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