0
public class StoreTxtFile implements Runnable {

@Override
public void run() {
    String id;
    String name;
    int age;
    int standard;
    String subject;

    Set keys = HumanDirectory.myMap.keySet();
    Iterator keyIterator = keys.iterator();

    try {
        Writer newFileWriter = new BufferedWriter
                        (new OutputStreamWriter
                        (new FileOutputStream("directory.txt"), "UTF-8"));
        while(keyIterator.hasNext()) {
            Human curHuman = HumanDirectory.myMap.get(keyIterator.next());
            id = curHuman.getId();
            name = curHuman.getName();
            age = curHuman.getAge();
            if(curHuman instanceof Student) {
                standard = ((Student) curHuman).getStandard();
                newFileWriter.write(id + " - " + name + " - " + age + " - " +  standard + "\n");
            }
            else if(curHuman instanceof Teacher) {
                subject = ((Teacher) curHuman).getSubject();
                newFileWriter.write(id + " - " + name + " - " + age + " - " +  subject + "\n");
            }
        }

    } catch (IOException ioe){
        ioe.printStackTrace();
    }
}
}

This code writes the contents of a directory (I used a MAP in the directory class) to a .txt file. The above thread is being executed in the main thread. Even debugging didn't help. Please explain why the file remains empty though being created.

Suva
  • 55
  • 2
  • 9
  • 1
    Call flush method once you finish writing, also close the writer once you have finished. – hanish.kh Dec 10 '13 at 05:23
  • 1
    Remember to **always** close the resources after using them. @hanish.kh when closing the stream, the buffer will be automatically flushed into the file. – Luiggi Mendoza Dec 10 '13 at 05:26
  • Actually if a huge amount of data is being written into, it's better to divide them into chunks and call flush. Closing automatically flushes the buffer though. – Suva Dec 10 '13 at 05:39

0 Answers0