-1

I wish to write name along with date and time onto a file for this i use an arraylist.But when i write it onto file..a single name along with date appears twice; It is related somewhere to my implying StandardOpenOption.Append because when I don't it prints date and values once but does overwrite my previous values.][1]

//created method to write date and name onto file

public void standardRoom() 
{
    try {
        Path p=Paths.get("test/standardRoom.text");

        if(Files.notExists(p))
        {
            Files.createFile(p);
        }
        System.out.println("Enter Name");
        String name=sc.next();

        List<String>stdrooms=new ArrayList<>();

        date = d.toString();

        stdrooms.add(date); 
        stdrooms.add(name);

        System.out.println("Standard Room booked");

        Iterator<String>bookings=stdrooms.iterator();
        while(bookings.hasNext())
        {              
            String s=bookings.next();
            //Files.write(p, stdrooms);
            Files.write(p, stdrooms,StandardOpenOption.APPEND);
        }
    } catch (IOException e) {
    }          


}
}
seedroots
  • 3
  • 2

1 Answers1

0

After adding date and name to the list, stdrooms contains two elements.

The iterator bookings now has the size of the list. Therefore Files.write is executed twice:

    Files.write(p, stdrooms,StandardOpenOption.APPEND);

When printing stdrooms containing both date and name, the default toString implementation is used, which in turn prints the whole list.

One solution might be to use s for printing instead of stdrooms:

    Files.write(p, s.getBytes(),StandardOpenOption.APPEND);
ldz
  • 2,217
  • 16
  • 21