ObjectInputStream.readObject()的问题!!!

hexiaofeng 2001-09-09 10:20:25
import java.io.*;
import java.util.*;

public class ree
{
public static void main(String args[])
{
try{
File file = new File("e.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Vector vector = new Vector();
String s = new String("wwww");
vector.add(s);
oos.writeObject(s);
oos.close();
fos.close();
}catch(IOException e){
System.out.println("IOException e");
}catch(ClassNotFoundException se){
System.out.println("ClassNotFoundException se");
}
}
}

//////////////////////////////////////////////////////////////////////

import java.io.*;
import java.util.*;

public class ree
{
public static void main(String args[])
{
try{
File file = new File("e.txt");
FileInputStream fos = new FileInputStream(file);
ObjectInputStream oos = new ObjectInputStream(fos);
Vector ob = (Vector)oos.readObject();
System.out.println(ob.toString());
oos.close();
fos.close();
}catch(IOException e){
System.out.println("IOException e");
}catch(ClassNotFoundException se){
System.out.println("ClassNotFoundException se");
}
}
}

////////////////////////////////////////////////////////////////////

class kk
{
int i;
String d;

}
/////////////
以上代码没问题,但改为
kk p = new kk();
p.i = 0;
p.d = "sd";
oos.writeObject(p);
////////////////////////////////
kk ob = (kk)oos.readObject();
////////////////////////////////
写入成功,无错误
但读的时候
kk ob = (kk)oos.readObject();
抛出 IOException 为什么???(写的时候都写入了) 如何才能读出一个 kk 类呢???
...全文
386 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
foxmike 2001-09-09
  • 打赏
  • 举报
回复
对于你的前两个程序,我有几个问题:
1.你第一个程序中写入的对象为String,而你第二个程序中读出的对象却为Vector.此时jdk会
有异常:java.lang.ClassCastException:java.lang.String。
2.第二个程序中要读出对象,所以要注意使程序能读出写入对象的文件:"e.txt",让e.txt在第
二个程序的根目录下。
3.关于类kk不能读出的问题,你看是不是上面的两个原因。但要注意的是要序列化的类必须要实现Serializable接口,例如这样:
class kk implements Serializable{
{
int i;
String d;

}.





kiddycoffee 2001-09-09
  • 打赏
  • 举报
回复
你这些语句是连在一起的吗?
kk p = new kk();
p.i = 0;
p.d = "sd";
oos.writeObject(p);
怎么又:
oos.readObject();
oos 到底是一个什么对象?
没看懂。

偶这里有一个 Sample,你看一下吧。

import java.io.*;

public class ObjIO implements Serializable
{
protected String field = "Hello, world.";

public ObjIO(String param){
field = param;
}

public void printit(){
System.out.println(field);
}

public static void main(String args[]) throws Exception
{
// writing ...
ObjectOutputStream objOut
= new ObjectOutputStream(new FileOutputStream("c:\\1.dat"));
ObjIO obj = new ObjIO("1");
objOut.writeObject(obj);
objOut.close();

// reading ...
ObjectInputStream objIn
= new ObjectInputStream(new FileInputStream("c:\\1.dat"));
ObjIO another = (ObjIO)objIn.readObject();
another.printit();
objIn.close();
}
}

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧