-2

I have an ArrayList W1 containing Ward type objects and each Ward object have a Ward Name,Max Capacity,Current Capacity and an ArrayList P1 containing Patient type objects. Each Patient type object have a Name,Age,Address,gender..etc

i want to write the ArrayList W1 to file using bufferedwriter and read that file using bufferedreader.

i do know how to read from an ArrayList and write to a file. but in this case it confusing me because i am trying to read from an ArrayList which contains objects with ArrayList.

Please tell me how to do this.

Thanks

is there any other ways rather than this,

public static void addWardToFile(Ward ward)
{
     try
    {            
        out = new BufferedWriter(new FileWriter("wardDetails.txt",true));

        Iterator itr = ward.wardPatients.iterator();

        String patient="";

        while(itr.hasNext())
        {
         patient += itr.next().toString() + ":"; //patient object have a overridden toString method
        }
        out.write(ward.name +","+patients);
        out.newLine();
        out.close();
    }
Mike
  • 11
  • 2
  • 6

2 Answers2

0

Use a nested for loop. Below is pseudocode:

for (w in W1){
    write w...
    for (p in w.P1){
        write p...
    }
}
holtc
  • 1,780
  • 3
  • 16
  • 35
0

try this:

public class test1 {

public static void main(String args[]) throws IOException{

    StringBuffer sb = new StringBuffer();
    String filepath = "test.txt";
    List<String> list = new ArrayList<String>(); 
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");
    list.add("5");
    list.add("6");

    Iterator<String> it = list.iterator();
    while(it.hasNext())
    {
        sb.append(it.next());
        sb.append(",");
    }

    BufferedWriter bw = new BufferedWriter(new FileWriter(filepath));
    bw.write(sb.toString());
    bw.flush();
    bw.close();
}

}

  • your example is perfect for an ArrayList with a simple elements(String,int,..etc).but in my case,my ArrayList W1 holds ward type objects,and a ward type object have a separate ArrayList to store ward patients. so i am asking how to store that ArrayList? should I store the W1 and store the ward patient ArrayList separate? – Mike Dec 29 '14 at 10:14
  • you can use like this: HashMap> hp = new HashMap>(); –  Dec 29 '14 at 11:13
  • or : List> list = new ArrayList>(); –  Dec 29 '14 at 11:13