将arraylist写入文本文件

时间:2011-12-19 19:01:39

标签: java arraylist writetofile

我有一个类Room的arraylist,它在类Hostel中保存,我想把这个arraylist写成一个文本文件。这样做最有效的方法是什么?

宿舍班级

public class Hostel
{
    private ArrayList < Room > rooms;
}

房间等级

abstract class Room
{

public Room(int newRoomNo, boolean newRoomEnSuite, int newRoomNights, String        newRoomBooker)
    {
        roomNo = newRoomNo;
        roomEnSuite = newRoomEnSuite;
        roomBooking = "Booked";
        roomNights = newRoomNights;
        roomBooker = newRoomBooker;
    }
}

4 个答案:

答案 0 :(得分:5)

来自commons-io

的单行
FileUtils.writeLines(new File(path), list);

答案 1 :(得分:3)

import java.io.*;
import java.util.ArrayList;

public class Hostel {
    public void writeRooms(ArrayList<Room> rooms){
        for (int i = 0; i < rooms.size(); i++) {
            write(rooms[i]);
        }
    }
    void write(Room room) throws IOException  {
        Writer out = new OutputStreamWriter(new FileOutputStream("FileName"));
        try {
          out.write(room.roomNo + ";" + roomEnSuite + ";" + roomBooking + ";" + roomNights + ";" + roomBooker + "/n");
        }
        finally {
          out.close();
        }
    }
}

这应该是不使用外部API的解决方案。

答案 2 :(得分:2)

您可以使用ObjectOutPutStream保存所有ArrayList

可以使用ObjectInputStream读取(重构)。可以通过使用流的文件来完成对象的持久存储。我

答案 3 :(得分:0)

尝试以下方面的内容:

abstract class Room
{
    public Room(int newRoomNo, boolean newRoomEnSuite, int newRoomNights, String newRoomBooker)
    {
        // ..
    }

    /* Each implementation of Room must be able to convert itself 
       into a line of text */
    @Override
    public abstract String toString();
}

class RoomWriter
{
    public void write(List<Room> rooms, File file) throws IOException
    {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        try
        {
            for (Room room : rooms)
            {
                writer.write(room.toString());
                writer.write("\n");
            }
        }
        finally
        {
            writer.close();
        }
    }

}