将数组从二进制文件输出到程序

时间:2016-03-03 17:14:43

标签: java arrays binary

我需要将发送到二进制文件的数组输出回我的程序。这是我到目前为止的代码......

Animal[] zoo =new Animal[9]; 
zoo[0]= new Hawk ("red tailed", 5); 
zoo[1]= new Hawk ("red tailed", 5); 
zoo[2]= new Hawk ("white tailed", 4); 

zoo[3]= new Elephant ("african elephant", 4);
zoo[4]= new Elephant ("african elephant", 4);
zoo[5]= new Elephant ("canadian elephant", 4);

zoo[6]= new Snake ("white tailed", 4);
zoo[7]= new Snake ("white tailed", 4);
zoo[8]= new Snake ("white tailed", 4);

Hawk h1=new Hawk("red hawk",5);

String fileName="out.bin";
try{
  FileOutputStream fileOs =new FileOutputStream(fileName);
  DataOutputStream os= new DataOutputStream(fileOs);
  os.writeUTF(h1.getname());
  os.writeInt(h1.getwing());
  os.close();
  System.out.println("Hawk info sent to binary file");
} catch (FileNotFoundException e){
  e.printStackTrace();
} catch (IOException e){
  e.printStackTrace();
}

try{
  FileInputStream fileOs =new FileInputStream(fileName);
  DataInputStream os= new DataInputStream(fileOs);
  System.out.println("Hawk info read from binary file: "+ os.readUTF()+"  "+ os.readInt());
  os.close();
} catch (FileNotFoundException e){
  e.printStackTrace();
} catch (IOException e){
  e.printStackTrace();
}  

String fileName1=("out.bin1");
try{
   FileOutputStream fileOs =new FileOutputStream(fileName1);
  ObjectOutputStream os= new ObjectOutputStream(fileOs);
  os.writeObject(zoo);
  //os.writeInt(h1.getwing());
  os.close();
  System.out.println("Animal array info sent to binary file");
} catch (FileNotFoundException e){
  e.printStackTrace();
} catch (IOException e){
  e.printStackTrace();
}

try{
  FileInputStream fileOs =new FileInputStream(fileName1);
  ObjectInputStream os= new ObjectInputStream(fileOs);
  //os.readObject((Animal)zoo); 
  System.out.println("Successfully transfered array data from binary file");
  os.close();
} catch (FileNotFoundException e){
  e.printStackTrace();
} catch (IOException e){
  e.printStackTrace();
}

} }

Soo基本上我没有编译器错误等将代码发送到二进制文件,但我只是不确定如何将其恢复...如果有人可以告诉我将非常感激。

提前致谢!!

1 个答案:

答案 0 :(得分:1)

readObject方法(https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#readObject())就是你想要的,你只需要将RESULT转换为你期望的类:

zoo=(Animal[])os.readObject();

它可能抛出其他异常,例如ClassNotFoundException。