Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

exclusive file access  RSS feed

peter repasy
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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).]
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!