I've got a Writer program that writes one line of text to a file, then waits until the user hits return before it writes another line and then exits. Only after that is the file closed. The code:
public class Writer {
Writer() {
}
public static String[] strings =
{
"Hello World",
"Goodbye World"
};
public static void main(String[] args)
throws java.io.IOException {
java.io.FileOutputStream pw =
new java.io.FileOutputStream("myfile.txt");
for(String s : strings) {
pw.write(s.getBytes());
System.in.read();
}
pw.close();
}
}
Start first with:
java Writer
Then I also have a reader program that should (well I expected) block as long as the writing of the file hasn't finished yet (i.e pw.close() has not been called yet). The code:
public class ReaderFIS extends Object {
ReaderFIS() {
}
public static void main(String[] args) throws Exception {
java.io.FileInputStream in = new java.io.FileInputStream("myfile.txt");
int ch = -1;
while((ch = in.read()) >= 0) {
System.out.println("ch = " + ch);
}
System.out.println("Last ch = " + ch);
System.out.println("exiting");
}
}
Start with:
java ReaderFIS
Now I expected the read() to block after reading the first "Hello World" text, based on this in the Javadoc documentation:
Reads a byte of data from this input stream. This method blocks if no input is yet available. Via: http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read()
But the ReaderFIS is immediately done after reading "Hello World" and apparently sees an EOF! So it does not block! It dumps the character values, then a -1 and then prints "exiting".
Output: ch = 72 ch = 101 ch = 108 ch = 108 ch = 111 ch = 32 ch = 87 ch = 111 ch = 114 ch = 108 ch = 100 Last ch = -1 exiting
Other variations I tried were: reading via a getChannel(), checking via getChannel() if it can be lock()ed, using available(), trying read() using a buffer, trying readLine(), continously writing a character in the file with a 500msec pause in between each write, not writing anything just keeping the file open in the Writer.
None of these variations cause the ReaderFIS program to block, it always finishes.
Why does the reader program not block? Did I miss something soooo very obvious? It seems the ReaderFIS program finds an EOF (-1) but why? The file has not been closed yet by the Writer program.
"Funny" sidenote: the System.in.read() is blocking! (and waiting for the user to hit Enter).
PS: tried this on Windows XP and Suse Linux. On Windows I can't delete the file while the writer is running (which is as I expected).
Regards, Marco