I have problem with file.I have application 1 and application 2 , application 1 create file (have process time). I want use from created file in application 2 when the process application 1 end. I use polling check for created file but can't understand file was closed or not(process application 1 end). Source application 1 locked and I want change source application 2.
-
While writing from application 1, save the file as `
.extension.part`. Once you finish writing, rename it to the name required. Hence, your application 2 will get the completed file – Karthik VU Mar 14 '17 at 18:15 -
I don't access to Application 1 source. – Morteza Jalambadani Mar 14 '17 at 18:16
-
Use a `try catch` in a `while(true)`. Keep trying to open the file. Once you are able to open the file, break from the loop. – Karthik VU Mar 14 '17 at 18:20
-
Need more information. can you paste code sample? – dev2d Mar 14 '17 at 18:22
-
You could use the Java WatchService API. You can create Watchers for files or directories – CocoNess Mar 14 '17 at 18:23
-
Possible duplicate of [Java: Check if file is already open](http://stackoverflow.com/questions/1390592/java-check-if-file-is-already-open) – M. Prokhorov Mar 14 '17 at 18:58
2 Answers
Since you don't have access to the app 1. The only thing we can do is from app 2.
If you are on a Windows system, the system will not allow you to change the file name if other process is reading/writing the file.
You can try to rename the output file from app 2. If it works fine, then the file wasn't opened by other process and you can start processing the output file. Of course you may wish change the file name back.
Please note, *NIX systems will have different behavior

- 858
- 6
- 22
You could use a temporary name for the file and then rename it to the proper name once it has been fully written.
You could create a ".lock" file to signal that it is locked for read or write. Once the reading or writing is complete you can delete the lock file. Each application should only read or write the file if the lock file is not present (and should create the lock file before performing its read or write operation and delete it as soon as it has finished).

- 12,285
- 4
- 43
- 66
-
Unfortunately, your answer requires control over all applications involved, and OP doesn't have control over application that would create a file. – M. Prokhorov Mar 14 '17 at 19:04
-