如何从.txt文件中读取数组的对象?

时间:2015-12-01 03:23:31

标签: arrays file object io stream

首先,我所做的是将一个ArrayList作为ann对象写入.txt文件,我要做的是将这些对象读回一个数组并显示数组(与第一步相反)。传递给功能的arraylist是推销员和技术人员,他们使用参数名称,编号,目标,特性等扩展员工。当我尝试编译时,我收到此错误。

线程中的异常" main" java.lang.ClassCastException:java.util.ArrayList无法强制转换为Employee     在FileIO.readObject(FileIO.java:165)     在UseCompany.main(UseCompany.java:61)

尝试从文本文件中读回对象

ArrayList<Employee> use_company_arraylist2 = FileIO.("C:\\Users\\Saad\\Documents\\writeObjectMethod.txt"");
use_company_arraylist2 = FileIO.readObject("C:\\Users\\Saad\\Documents\\writeObjectMethod.txt");

写入文本文件代码的对象:

public static void writeObject(ArrayList<Employee> array_of_employee, String    filename)
{
  try{

     //create file stream and write array to file using stream using objectoutput stream
     FileOutputStream fle = new FileOutputStream("c:\\Users\\Saad\\Documents\\writeObjectMethod.txt");
     ObjectOutputStream oos = new ObjectOutputStream(fle);
     oos.writeObject(array_of_employee);
     oos.close();
     fle.close();
  }

  catch(FileNotFoundException filenotfound)
  {  
     System.out.println("FILE NOTE FOUND");
  }
  catch(IOException ioerror)
  {
     System.out.println("input or output error");
  }


}//end writeObject 

来自文本文件代码的阅读对象:

 public static ArrayList<Employee> readObject (String filename)
{
  ArrayList<Employee> newArrayList = new ArrayList<Employee>();

  try 
  {  
     FileInputStream readfle = new FileInputStream(filename);
     ObjectInputStream readobjectfile = new ObjectInputStream(new BufferedInputStream(readfle));
     newArrayList.add((Employee)readobjectfile.readObject());

  }

  catch(ClassNotFoundException clasnfd)
  {
     System.out.println("class error?");
  }


  catch(IOException ioerror)
  {
     System.out.println("input or output error");
  }
  return newArrayList;

}//end readObject

1 个答案:

答案 0 :(得分:0)

Arraylist类型的对象无法转换为Employee类的对象。

这会奏效     ArrayList list = new ArrayList();     list.add(new Employee());

// for writing arraylist object to file
new ObjectOutputStream(new FileOutputStream(new File("a.txt"))).writeObject(list);

// for reading array list from file
ArrayList<Employee> anotherList = (ArrayList<Employee>) new ObjectInputStream(new FileInputStream(new File("a.txt"))).readObject();

System.out.println(anotherList.size());