Reputation: 1310
I am wondering what would happen if I tried to read files in Java which might be modified by another processes. For example given the pseudocode:
File f = new File("a");
if (f.exists()) {
// A
BufferedReader br = new BufferedReader(new FileReader(f));
// B
String line = "";
while ((line = br.readLine() ) != null ) {
// C
out.println(line);
}
}
What would happen if at those commented places (A/B/C) the file name had been changed by another process? Would it differ if instead the file was removed or replaces by another? Would any of that be affected if different kind od file reading was implemented?
Upvotes: 2
Views: 1554
Reputation: 310883
You can, and should, eliminate point A by removing the exists()
test and catching FileNotFoundException,
and once you have the file open it doesn't matter to you what it's called, and on some operating systems it is impossible to rename an open file. Also, there is no reason to initialize the 'line' variable.
Upvotes: 3
Reputation: 386
If different processes are touching your file, the if(f.exists()) logic won't help you much: The result could be different by the time it finishes executing but before your next line does.
If the filename of the file changes at point //A, you're going to get a FileNotFoundException according to the FileReader documentation. If the file is replaced by another reader oughtn't notice.
After this point, your VM should have control of the file and most OSs will prevent other processes from touching the file.
Concurrent modification of files is a bad idea though, and should be avoided. If you're trying to find a way to get two processes to communicate, a common option is to use memory-mapped files. Again, another solution would probably be much more sound.
Upvotes: 3