St.Antario
St.Antario

Reputation: 27385

Isn't it possible for a file to not be visible for other processes?

I have a Java application which is invoked from a shell script and creates a file, then writes some content to it. It works something like this:

File f = new File("/tmp/NEW_t.zip");
try(FileOutputStream fos = new FileOutputStream(f);
    Writer writer = new OutputStreamWriter(fos)){
  writer.write("Test string");
  writer.write("another test string");
  //lots of other writings

The resulting file will be quite large (up to 100MB). The issue is that opening the FileOutputStream creates an empty file and makes it available to other processes in the system.

In my case it causes a nasty bug because another process can read this file in an inconsistent state (empty).

Is it possible to make this file invisible for other processes until the process which created it has finished with it? Can it be resolved at the OS level or is there another solution?

Upvotes: 0

Views: 162

Answers (2)

Christopher Hostage
Christopher Hostage

Reputation: 143

Another way to do it is to store the file as .tmp or another naming convention until your first process is done with it completely, then rename it to the expected ingestion name. There are other, better ways of doing it in a program, but that's a question better answered in StackOverflow.

Upvotes: 3

DrNoone
DrNoone

Reputation: 261

You could make the file not accessible to other process by setting the file permissions to 700 (full access owner, no access same group as owner, no access other users), or by using the UMASK settings when you create the file. Once you finished you can enable the access to the file.

In java, you can do that by using setPosixFilePermissions

Upvotes: 1

Related Questions