在java中下载文件时如何检测到网络断开连接? [英] How do you detect a network disconnection when downloading a file in java?

查看:561
本文介绍了在java中下载文件时如何检测到网络断开连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码使用Java下载文件,但是我想在连接丢失时检测。我运行了以下代码,而在下载中,我有意识地断开了我的互联网,但没有例外被抛出,它挂起。即使打开连接后也没有发生任何事情。所以,它永远挂在没有任何例外。有没有办法使连接丢失时引发异常?感谢您的帮助!

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 disconnected my internet purposefully but no exception was thrown and it hanged. Even after turning on the connection back nothing happened. So, it hanged forever without any exceptions. Is there a way to make it 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...");


        }
    }


推荐答案

由于您使用HTTP,您最好使用 Apache HttpClient 项目。 org.apache.http.client.config.RequestConfig.Builder 允许设置java.net.URL和相关类中没有对应关系的各种超时值。特别设置套接字超时将有助于您的情况。然后,您可以使用 org.apache.http.HttpEntity.writeTo 直接将资源写入FileOutputStream。

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.

这篇关于在java中下载文件时如何检测到网络断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆