Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if file is completely written [duplicate]

Tags:

Currently I'm working on the project that does processing files from source directory in one of it's routines. There's a Java process that's looking for specified directory and tries to read and process files if they exist. Files are quit large and updates by other thirdparty process. The question is how can I check if the file is completely written? I'm trying to use file.length() but looks like even if writing process hasn't been completed it returns actual size. I have a feeling that solution should be platform dependent. Any help would be appreciated.

UPDATE: This question is not really different from the duplicate but it has an answer with working code snippet that is highly rated.

like image 763
Viktor Stolbin Avatar asked Jun 28 '12 06:06

Viktor Stolbin


People also ask

How can I tell if a file is completely written?

Another approach is to have one process write the file with a name that your process won't recognize, then rename the file to a recognizable name when the write is complete. On most platforms, the rename operation is atomic if the source and destination are the same file system volume.

How can I tell if a file is in use Python?

Checking If a Certain File or Directory Exists in Python In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False.


1 Answers

I got the solution working:

private boolean isCompletelyWritten(File file) {     RandomAccessFile stream = null;     try {         stream = new RandomAccessFile(file, "rw");         return true;     } catch (Exception e) {         log.info("Skipping file " + file.getName() + " for this iteration due it's not completely written");     } finally {         if (stream != null) {             try {                 stream.close();             } catch (IOException e) {                 log.error("Exception during closing file " + file.getName());             }         }     }     return false; } 

Thanks to @cklab and @Will and all others who suggested to look in "exclusive lock" way. I just posted code here to make other interested in people use it. I believe the solution with renaming suggested by @tigran also works but pure Java solution is preferable for me.

P.S. Initially I used FileOutputStream instead of RandomAccessFile but it locks file being written.

like image 192
Viktor Stolbin Avatar answered Nov 09 '22 06:11

Viktor Stolbin