permaculture playing cards
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
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "exclusive file access" Watch "exclusive file access" New topic

exclusive file access

peter repasy

Joined: May 10, 2001
Posts: 1
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?
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:

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");


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

int nBytes = fin.available();
for(int i = 0; i < nBytes; ++i) {


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!


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

I agree. Here's the link:
subject: exclusive file access
jQuery in Action, 3rd edition