import java.io. * ; public class Ser { public static void main(String args[]) { try { John myObj = new John("Sachin","Cricket"); System.out.println(myObj); FileOutputStream fos = new FileOutputStream("FileName"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(myObj); oos.flush(); oos.close(); } catch (Exception e) { System.out.println("Expection" + e); System.exit(0); } try { John myObj2; FileInputStream fis = new FileInputStream("FileName"); ObjectInputStream ois = new ObjectInputStream(fis); myObj2 = (John) ois.readObject(); ois.close(); System.out.println("New Object" + myObj2); } catch (Exception e) { System.out.println("Expection" + e); System.exit(0); } } } class John implements Serializable { private String name; private String department; public John(String name,String department) { this.name = name; this.department = department; } public String toString() { return "Name" + name + " " + "Department" + department; } }
我在上面的例子中有几个问题.
>何时使用冲洗方法,为什么要使用它?
> close方法在这里得分是多少?
> myObj2 =(John)ois.readObject(); …请纠正我,如果我错了,我正在读取文件对象并存储到另一个对象并转换为文件对象.
>使用Java进行序列化或持久化数据的替代方法有哪些.我不希望数据作为字节流进入文件.
解决方法
When to use flush method and why do we use it?
它会刷新仍然由OutputStream缓冲的任何内容.详细说明可在JavaDoc中找到.
What does close method carry a score here?
我不确定你的意思是“带分”,但是close方法最终会关闭资源(输入或输出),它会释放,例如文件句柄.您应该始终在finally块中调用close来清理操作系统可能具有的所有引用.
InputStream is = null; try { is = new FileInputStream(...); // do stuff } catch (IOException e) { // do stuff } finally { if (is != null) { is.close(); } }
myObj2 = (John) ois.readObject(); … please correct me if i am wrong,
i am reading the file object and storing into another object and
typecasting the file object.
以某种方式更正,您之前反序列化写入文件的对象.这些文件是专有的,只能被Java理解,所以你最后一个问题是好的!
What are the alternatives of Serialization or persisting the data in
Java. I don’t want the data to get into file as byte stream.
你有很多选择.对于客户端应用程序,您可能希望使用XML,JSON或轻量级数据库(如sqllite).在服务器端,您也可以查看更强大的数据库(例如MysqL).