【发布时间】:2016-03-04 21:09:51
【问题描述】:
首先我所做的是将 ArrayList 作为 ann 对象写入 .txt 文件,我要做的是将这些对象读回数组并显示数组(与第一步相反)。我传递给函数的数组列表是推销员和技术人员,他们使用参数名称、编号、目标、区域等扩展员工。当我尝试编译它时出现此错误。
线程“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
【问题讨论】:
标签: arrays file object io stream