How do you detect network disconnect when loading a file in java?

I use the following code to download a file using Java, but I want to determine when the connection is lost. I ran the following code, and, in the middle of the download, I disconnected my Internet purposefully, but there were no exceptions, and he hanged himself. Even after turning on the connection, nothing happened. Thus, he hanged himself forever without any exceptions. Is there a way to get it to throw an exception when the connection is lost? Thanks for the help!

package toplower.top; import java.io.FileOutputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.*; import javax.mail.*; public class testing { public static void main(String[] args) { try{ URL website = new URL("http://b128.ve.vc/b/data/128/1735/asd.mp3"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("song.mp3"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch(Exception e){ System.out.println("got here"); e.printStackTrace(); } System.out.println("Done downloading..."); } } 
+1
source share
2 answers

Apparently, one can 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 is blocked forever - and this is your root problem. Thus, one possible solution would be to switch to asynchronous operations and / or set a timeout

0
source

Since you are using HTTP, your best bet is to use Apache HttpClient . org.apache.http.client.config.RequestConfig.Builder allows you to set different timeout values ​​that do not have a match in java.net.URL and related classes. Especially if setting a socket timeout will help in your case. Then you can use org.apache.http.HttpEntity.writeTo to directly write the resource to FileOutputStream.

0
source

All Articles