开发者

download file exception handling

In my application I download several critical files from a server, and I want to write some code that handles the case where the a file download didn't complete for a reason or other ,to retry downloading it at next startup. The function that downloads a file at a time however throws only MalformedURLException and IOException , but if these exceptions are thrown that means that the download didn't even begin. How should I arrange things so I can treat the case where a download failed , even if it began ?

void download(String file) throws MalformedURLException ,IOException 
{

        BufferedInputStream getit = new BufferedInputStream(new URL(file).openStream());
        FileOutputStream saveit = new FileOutputStre开发者_StackOverflow中文版am(DOWNLOAD_PATH+fileName+"."+ZIP_EXTENSION);
        BufferedOutputStream bout = new BufferedOutputStream(saveit,1024);
        byte data[] = new byte[1024];
        int readed = getit.read(data,0,1024);
        while(readed != -1)
        {
            bout.write(data,0,readed);
            readed = getit.read(data,0,1024);
        }
        bout.close();
        getit.close();
        saveit.close();

}


You might be better using the Jakarta Commons HttpClient API.

However, for your custom function take a look at InterruptedIOException and bytesTransferred on https://docs.oracle.com/javase/1.5.0/docs/api/java/io/InterruptedIOException.html

public class InterruptedIOException
extends IOException

Signals that an I/O operation has been interrupted. 

The field bytesTransferred indicates how many bytes were successfully transferred before the interruption occurred. 


If your download is synchronous, you should be able to add an appropriate exception (or return an appropriate value) to indicate failure.

If your download is asynchronous, consider using the observer pattern. You can pass in an observer implementation as an extra parameter to your download method.

The observer in your case (for example) might look something like:

public interface FileDownloadObserver
{
  public void downloadFailed(String file, Object error);
  public void downloadSucceeded(String file);
}

Then the download method would look like:

void download(String file, FileDownloadObserver observer)
    throws MalformedURLException, IOException

This is all assuming you can actually detect that the download failed. If not, you might have to provide some more information about how you're doing the download.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜