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..."); } }
source share