用ObjectInputStream读二进文件

suofeya 2012-10-31 10:41:44
不知道哪出问题了 总是报IOException异常 ObjectOutputStream使用writeInt()方法正确写入数据的 但在ObjectInputStream中用readInt()方法 不能读出来


import java.io.*;
public class two02 {
public static void input(){
ObjectInputStream in=null;
try{
in=new ObjectInputStream(new FileInputStream("01.dat"));
for(int i=0;i<3;i++){
int t=in.readInt();
System.out.println(t);
}
in.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
}
catch(IOException e){
System.out.println("wrong read");
}
}
public static void main(String args[]){
input();
}
}
...全文
180 5 打赏 收藏 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
faping_cao 2012-12-20
  • 打赏
  • 举报
回复
ObjectOutputStream writeInt 对应 ObjectInputStream readInt
tessykandy 2012-11-01
  • 打赏
  • 举报
回复
可能原因:writeInt的个数少于readInt的个数, 下面代码经测试没问题

import java.io.*;

public class TestIO {
private final static int COUNT = 3;
private final static String fileName = "01.dat";

public static void input() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(fileName));
for (int i = 0; i < COUNT; i++) {
int t = in.readInt();
System.out.println(t);
}
in.close();
} catch (FileNotFoundException e) {
System.out.println("file not found");
} catch (IOException e) {
System.out.println("wrong read");
}
}

public static void write() {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(fileName));
for (int i = 0; i < COUNT; i++) {
out.writeInt(i);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String args[]) {
write();
input();
}
}

suofeya 2012-11-01
  • 打赏
  • 举报
回复
不能打印出数字 而是进入IOException中,打印出wrong read
wufei151 2012-11-01
  • 打赏
  • 举报
回复
你先把错误异常输出来看一下。。

62,620

社区成员

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

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