Writing arraylist to textfile

放肆的年华 提交于 2019-12-25 06:48:20

问题


I have an arraylist of class Room which is held in class Hostel, i would like to write this arraylist to a text file. What is the most efficient method of doing so?

Hostel Class

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

Room Class

abstract class Room
{

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

回答1:


A one-liner from commons-io

FileUtils.writeLines(new File(path), list);



回答2:


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();
        }
    }
}

This should be a solution without using external API.




回答3:


You can use ObjectOutPutStream to save all ArrayList

and can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. I




回答4:


Try something along the lines of:

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();
        }
    }

}


来源:https://stackoverflow.com/questions/8566088/writing-arraylist-to-textfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!