Talk:Code snippets:File I/O
From MDC
For enumerating files in given directory, I found that getNext() would sometimes return null, causing an infinite loop. I solved this with:
while(entries.hasMoreElements() && (entry = entries.getNext()) != null){
entry.QueryInterface(Components.interfaces.nsIFile);
//asdf
}
- I don't belive getNext() should null when hasMoreElements returns true. What OS do you use? Can you figure out when this happens? If yes, please file a bug. --Nickolay 17:20, 18 January 2007 (PST)
- Perhaps it occurs when a file which existed when the enumeration was created has been deleted from the underlying file system? I'm assuming that enumerations are created statically and not dynamically as hasMoreElements() is called. --Grimholtz 17:25, 18 January 2007 (PST)
- At least on windows it happens dynamically. I have actually looked at the code before posting. --Nickolay 18:26, 18 January 2007 (PST)
- I can still see a race condition where the file mightn't exist: the code calls hasMoreElements() on the enumeration, which returns true. Now before getNext() is called, the file which would have been returned is deleted by another process. We can easily write code to test this scenario by placing an abnormally long delay (e.g., via alert()) between hasMoreElements() and getNext() and manually deleting the file before next() is called. I don't know if null would be returned by getNext() in this situation, but it's worth trying. --Grimholtz 18:42, 18 January 2007 (PST)
- At least on windows it happens dynamically. I have actually looked at the code before posting. --Nickolay 18:26, 18 January 2007 (PST)
- Perhaps it occurs when a file which existed when the enumeration was created has been deleted from the underlying file system? I'm assuming that enumerations are created statically and not dynamically as hasMoreElements() is called. --Grimholtz 17:25, 18 January 2007 (PST)
--
fwiw, I don't think the code to write binary data to a file will work. nsIOutputStream doesn't really handle null bytes very well. Not to mention, of course, that it uses a string whereas the reading code uses a byte array. --biesi 18:49, 15 March 2007 (PDT)