How to check filelock without trimming a file?

I recently added file blocks to my asynchronous download:

FileOutputStream file = new FileOutputStream(_outFile); file.getChannel().lock(); 

and after the download is complete, file.close() to release the lock.

From the called BroadcastReceiver (another thread), I need to go through the files and see which ones are downloaded and which are still locked. I started with trylock:

 for (int i=0; i<files.length; i++) { try { System.out.print((files[i]).getName()); test = new FileOutputStream(files[i]); FileLock lock = test.getChannel().tryLock(); if (lock != null) { lock.release(); //Not a partial download. Do stuff. } } catch (Exception e) { e.printStackTrace(); } finally { test.close(); } } 

Unfortunately, I read that the file is truncated (0 bytes) when creating FileOutputStream. I set it to add, but the lock does not seem to take effect, everything seems not to be locked (fully loaded)

Is there another way to check if file write lock is currently in use, or am I using the wrong methods here? Also, is there a way to debug file locks from an ADB or Eclipse terminal?

+4
source share
2 answers

None of this will work. Check out the Javadoc. Locks are held on behalf of the entire process, i.e. JVM, not individual threads.

+2
source

My first thought is to open it for adding to javadocs

 test = new FileOutputStream(files[i], true); // the true specifies for append 
+2
source

Source: https://habr.com/ru/post/1437723/


All Articles