wood burning stoves 2.0*
The moose likes I/O and Streams and the fly likes exclusive file access Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "exclusive file access" Watch "exclusive file access" New topic
Author

exclusive file access

peter repasy
Greenhorn

Joined: May 10, 2001
Posts: 1
Hi,
as i figured out it is possible to open two FileOuputStream objects to the same file and use them simultaneously:
fout1 = new FileOutputStream("a.bin");
...
fout2 = new FileOutputStream("a.bin");
Now i expect the second (or any other attempt) to fail because the file is already open for writing. How does this work in java?
Peter
Ryan Langley
Ranch Hand

Joined: May 10, 2001
Posts: 46

You may have more than one open OutPutStream to the same file in JAVA. Here is a quick code example:



<>
import java.io.*;
public class FileOut {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileOutputStream fout1 = new FileOutputStream("a.bin");
FileOutputStream fout2 = new FileOutputStream("a.bin");

PrintStream ps1 = new PrintStream(fout1);
PrintStream ps2 = new PrintStream(fout1);

ps1.println("String written to fout1");
ps2.println("String written to fout2");

ps1.close();
ps2.close();
fout1.close();
fout2.close();

FileInputStream fin = new FileInputStream("a.bin");

int nBytes = fin.available();
for(int i = 0; i < nBytes; ++i) {
System.out.print((char)fin.read());
}

fin.close();
}
}



This code will open two separate streams to the same file and write the strings to it in the order shown. Try it for yourself.


I think the only time you would have a problem with this is if you had multiple threads accessing the same file. There would be a possibility, although slight, that two or more threads may try to write to the file at the same time, which would cause a runtime error.


Hope this was informative!


RL


[This message has been edited by Ryan Langley (edited May 11, 2001).]


Cheers,<P>RL
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: exclusive file access