简体   繁体   English

将数据从对象的数组列表和对象内的数组列表写入文本文件

[英]write data from an arraylist of objects and arraylist within objects to a text file

say i have a an arraylist that contains objects of type employee that have instance variables such as id,first name, last name, tel and also with each object there is another arraylist that contains numerical data and I want to write all that data out to a txt file , what would be the best way of doing this 说我有一个arraylist,其中包含employee类型的对象,这些对象具有实例变量,例如id,名字,姓氏,tel,并且每个对象还有另一个包含数字数据的arraylist,我想将所有这些数据写到一个txt文件,什么是最好的方法

My current thinking is that I could iterate through with a for loop the first arraylist to write the instance variables, then have a inner for loop to make get calls to the arraylist in the objects. 我目前的想法是,我可以使用for循环遍历第一个arraylist来写入实例变量,然后使用内部的for循环对对象中的arraylist进行get调用。 I have got the first for loop working and writing, just trying to work out how to get the second inner loop to get the other data. 我有第一个for循环工作和编写程序,只是试图弄清楚如何获取第二个内部循环来获取其他数据。 It is important that the data is written in the correct order which is id, firstname, lastname, tel and then followed by the numerical data in the order it is stored, then on to the next employee to write in the same order. 重要的是,以正确的顺序(即id,firstname,lastname,tel)写入数据,然后按照存储顺序依次输入数字数据,然后以下一个顺序写入下一个员工。

Im not sure how how to achieve this exactly and am still experimenting with the code but would appreciate to suggestions on how best to go about this. 我不确定如何准确地实现此目标,并且仍在尝试代码,但希望您能就如何最好地做到这一点提出建议。

UPDATE 更新

Seems like I have it working - i did the following: 似乎我可以使用它-我做了以下工作:

PrintStream out = new PrintStream (new FileOutputStream("output.txt")); 
    for (int a=0;a<emp.size();a++)
    {
    empNumber = emp.get(a).empNumber;
    out.println(empNumber); 
    fName = emp.get(w).fName;
    out.println(fName); 
    lName = emp.get(w).lName;
    out.println(lName); 
    telNum = emp.get(w).telNum;
        for (int l=0;l<emp.get(w).dataNums.size();l++)
        {
            out.println(emp.get(w).dataNums.get(l));
        }

    out.close();    
    }

There are probably much more sophisticated ways but Im happy enough as a beginner I worked it out myself. 可能有很多更复杂的方法,但是作为一个初学者,我很高兴我自己解决了这个问题。

thanks for the replies though 谢谢你的答复

The best way in my opinion is to implement a toString() method for each one of your objects. 我认为最好的方法是为每个对象实现一个toString()方法。 Then just use toString() on your arrayList with employee. 然后,只需在雇员的arrayList上使用toString()即可。 And lastly use for example fileWriter to write this String to a txt. 最后使用例如fileWriter将此字符串写入txt。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM