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
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
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.