This question is not answered. Helpful answers available: 2. Correct answers available: 1.


Permlink Replies: 2 - Pages: 1 - Last Post: 16-Jan-2018 14:12 Last Post By: davidekholm Threads: [ Previous | Next ]
Dschuwi

Posts: 1,528
Registered: 12-Nov-2003
File copy coding example - which approach is better
Posted: 16-Jan-2018 12:50
 
  Click to reply to this thread Reply
As a follow-up to a thread in the bugs forum, in general, for cases when it is unknown whether the source file exists, is it good practice to copy a file like this (seized working in jAlbum 15)

try {
  IO.copyFile(f, r);
}
 catch(IOException e) {}

or better to perform a file existence check instead

if (f.exists()) {
  IO.copyFile(f, r);
}
 
jGromit

Posts: 33,459
Registered: 31-Jan-2006
Re: File copy coding example - which approach is better
Posted: 16-Jan-2018 14:00   in response to: Dschuwi in response to: Dschuwi
 
  Click to reply to this thread Reply
You might still need an error trap, because the file copy might fail for other reasons.

The source file might exist, but might be locked. This happens in Windows with media files like MP3 and MP4 if you've opened the file in your browser, and the browser is still open, even if you've closed the file. You actually have to close the browser to avoid the error.

Or the destination directory might not exist, or be "read-only."
davidekholm

Posts: 21,772
Registered: 18-Oct-2002
Re: File copy coding example - which approach is better
Posted: 16-Jan-2018 14:12   in response to: jGromit in response to: jGromit
 
  Click to reply to this thread Reply
It's never wrong to perform an existence check. v15.1.5 is now fixed to properly throw a FileNotFoundException if the source file is missing before attempting to delete the target file. (The target file deletion was added when introducing hard links. Without it, there is a risk that the source file gets truncated to zero bytes).

Also remember to put the catch clause after any other code that relies on that successful copy.
Legend
Forum admins
Helpful Answer
Correct Answer

Point your RSS reader here for a feed of the latest messages in all forums