【问题标题】:How to read objects of arrays from a .txt file?如何从 .t​​xt 文件中读取数组对象?
【发布时间】: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


    【解决方案1】:

    Arraylist 类型的对象不能转换为 Employee 类的对象。

    这会起作用 ArrayList 列表 = 新的 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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多