[英]Reading bytes from a deserialized file
我將在本教程之后學習Java序列化。 我已經使用以下代碼(省略了導入)從序列化文件中成功讀取並使用了我的對象:
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();
}
}
}
但是,序列化對象的主要目的是可以將其推送到Redis存儲。 因此,為此,我不需要以對象形式而是字節形式。 所以我將最后一個try塊的內容更改為...
while(true){
try{
System.out.println(ois.readByte());
} catch(EOFException eofe){
eofe.printStackTrace();
break;
}
}
但這會立即引發EOFException。 我做錯了什么嗎?
對象流被標記。 這意味着,如果您閱讀的信息類型與期望的信息類型不同,則可能會感到困惑,從而導致EOFException,而不是像IllegalStateException這樣的有意義的錯誤消息。
如果要由ObjectOutputStream寫入的字節,最簡單的操作是僅使用內存。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream ois = new ObjectOutputStream(baos);
ois.writeObject(object);
ois.close();
byte[] bytes = baos.toByteArray();
如果您想將實例推送到redis,則可以使用JRedis 。
來自文檔的示例代碼。
// 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.