On Tue, 02 May 2006 14:38:50 -0700 "Jim C." <[EMAIL PROTECTED]> wrote:
> Stefaan A Eeckels wrote: > > On Mon, 01 May 2006 13:41:12 -0700 > > "Jim C." <[EMAIL PROTECTED]> wrote: > > > >> Anyone know how a simple file copy can be accomplished in an > >> explicitly synchronous manner without adding Thread.sleep(n) after > >> calling flush on the output stream? > > > > Have you tried the streams method from the same site: > > > > http://javaalmanac.com/egs/java.io/CopyFile.html > > > Yes. Same problem. If you're doing the copy in a separate thread, you'll need to synchronize that thread (which is a producer) and the thread that needs the file (which is a consumer). wait()/notifyAll() can be used to ensure that a consumer will wait for the producer to terminate and vice-versa: public synchronized void useFile() { while (copyDone == false) try { //Wait for copyFile to finish the copy. wait(); } catch (InterruptedException e) { } // Reset the flag copyDone = false; // Use the copy performTestOnFile(); // Tell copyFile we're done notifyAll(); } public synchronized void copyFile(String src, String dst) { while (copyDone == true) try { // Wait for the test to use the file copy wait(); } catch (InterruptedException e) { } try { // Create channel on the source FileChannel srcChan = new FileInputStream(src).getChannel(); // Create channel on the destination FileChannel dstChan = new FileOutputStream(dst).getChannel(); // Copy file contents from source to destination dstChannel.transferFrom(srcChan, 0, srcChan.size()); // Close the channels srcChan.close(); dstChan.close(); } catch (IOException e) { } copyDone = true; // Tell the test method the file is ready notifyAll(); } Please note that I didn't test this :-) Alternatively, you can do the copy and execute the test in the same thread which would make sure the copy is finished before you get to executing the test. Take care, -- Stefaan -- As complexity rises, precise statements lose meaning, and meaningful statements lose precision. -- Lotfi Zadeh ---------------------------------------------------------------------- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]