How do you detect a network disconnection when downloading a file in java?

后端 未结 2 1632
花落未央
花落未央 2021-01-07 07:01

I am using the following code to download a file using Java but i want to detect when connection is lost. I ran the following code and while in the middle of downloading i d

相关标签:
2条回答
  • 2021-01-07 07:25

    apparently one is able to set a timeout on your socket, i think this article describes it : http://technfun.wordpress.com/2009/01/29/networking-in-java-non-blocking-nio-blocking-nio-and-io/

    Your current thread blocks forever - and thats your root problem. So one possible solution would be to switch to asynchronous operations and/or to set your timeout

    0 讨论(0)
  • 2021-01-07 07:35

    Since you are using HTTP, you would be best of using the Apache HttpClient project. org.apache.http.client.config.RequestConfig.Builder allows to set various timeout values that have no correspondence in java.net.URL and related classes. Especially setting a socket timeout would help in your case. You can then use org.apache.http.HttpEntity.writeTo to directly write the resource to a FileOutputStream.

    0 讨论(0)
提交回复
热议问题