Darren Burgess
Darren Burgess

Reputation: 4322

Writing arraylist to textfile

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

Upvotes: 0

Views: 8035

Answers (4)

user1105826
user1105826

Reputation:

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

Upvotes: 2

Binil Thomas
Binil Thomas

Reputation: 13809

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

}

Upvotes: 0

domes
domes

Reputation: 66

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.

Upvotes: 3

Bozho
Bozho

Reputation: 597392

A one-liner from commons-io

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

Upvotes: 5

Related Questions