0

我有一个类的数组列表,Room它保存在类中Hostel,我想将此数组列表写入文本文件。这样做最有效的方法是什么?

宿舍类

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

4 回答 4

5

来自commons-io 的单线

FileUtils.writeLines(new File(path), list);
于 2011-12-19T19:14:56.127 回答
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 的解决方案。

于 2011-12-19T19:17:29.480 回答
2

您可以使用 ObjectOutPutStream 保存所有 ArrayList

并且可以使用 ObjectInputStream 读取(重构)。对象的持久存储可以通过使用流的文件来实现。一世

于 2011-12-19T19:47:26.700 回答
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();
        }
    }

}
于 2011-12-19T19:19:28.640 回答