用ObjectInputStream读二进文件
不知道哪出问题了 总是报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();
}
}
--------------------编程问答-------------------- 你先把错误异常输出来看一下。。 --------------------编程问答-------------------- 不能打印出数字 而是进入IOException中,打印出wrong read --------------------编程问答-------------------- 可能原因:writeInt的个数少于readInt的个数, 下面代码经测试没问题
--------------------编程问答-------------------- 除 --------------------编程问答-------------------- ObjectOutputStream writeInt 对应 ObjectInputStream 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();
}
}
补充:Java , Java SE