java 怎么把多个对象写进同一个文件里,用集合

解决方案 »

  1.   

    定义个List啊!   
    List l=new ArrayList();
    l.add(object);
      

  2.   


    public List<Employee> findAll() throws SQLException {
    /*
     * 用DB工具类连接数据库,用PreparedStatement()方法将sql语句发送到数据库
     * 用executeQuery()方法执行操作
     */
    Connection conn = DBUtil.getConnection();
    PreparedStatement ps = conn.prepareStatement(FINDALL);
    ResultSet rs = ps.executeQuery();
    List<Employee> employees =  new ArrayList<Employee>();
    /*
     * 用while循环sql语句的结果,并把它添加到 employees集合中
     */
    while(rs.next()){//rs是结果集,迭代 将rs全部进行读取
    Employee e = new Employee();
    e.setId(rs.getLong("id"));
    e.setEname(rs.getString("ename"));
    e.setGender(rs.getString("gender"));
    e.setAge(rs.getInt("age"));
    e.setSalary(rs.getDouble("salary"));
    e.setDeptno(rs.getLong("deptno"));
    employees.add(e);
    }
    //关闭连接
    DBUtil.close(conn);
    return employees;
    }
      

  3.   

    用ObjectOutputStream把对象写入文件中。。如果是多个对象,可以试试把对象add到HashSet或ArrayList中。。
      

  4.   


    FileOutputStream fos = new FileOutputStream("e:\\xxx");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    Set set = new HashSet();
    Student s1 = new Student();
    Student s2 = new Student();
    set.add(s1);
    set.add(s2);
    oos.writeObject(set);

    oos.close();
    fos.close();