Java从web服务器下载文件到本地

本文提供了一个使用Java从服务器下载文件到本地的示例代码。该方法通过建立URL连接并设置超时时间来确保文件可以被可靠地获取。此外,还展示了如何处理不同类型的异常,如URL错误、文件未找到等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*从服务器中下载文件到本地*/
/*url:文件存放在服务器的地址;target:要保存的路径*/     
 
public String DownloadFile(String url,String target){
          URLConnection con=null;
          URL theUrl=null;
          try {
              theUrl=new URL(url);//建立地址
              con = theUrl.openConnection();//打开连接
              con.setConnectTimeout(30000);
              con.connect();//连接
          } catch (MalformedURLException e) {
              Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
              return "给定的URL地址有误,请查看";
          }
          catch (IOException e) {
              Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
              return "无法连接到远程机器,请重试!";
          }
          jLabel5.setText("√");
          Process++;
          File file = new File(gbl_ParentPath+"/UpdateTemp");
          if(file.exists()==false){
              file.mkdir();
          }
          String type = con.getContentType();
          if (type != null) {
              byte[] buffer = new byte[4 * 1024];
              int read;
              try {
                  FileOutputStream os = new FileOutputStream(target);
                  InputStream in = con.getInputStream();//重定向输入
                  while ((read = in.read(buffer)) > 0) {//读取输出
                      os.write(buffer, 0, read);//写入本地文件
                  }
                  os.close();
                  in.close();
                  jLabel6.setText("√");
                  Process++;
              } catch (FileNotFoundException e) {
                  Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
                  return "所要下载的文件不存在!";
              }catch (IOException e) {
                  Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
                  return "读取远程文件时出错!";
              }
          } else {
              return "文件未找着:"+url;
          }
          return "";
      }
 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值