国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java使用http實現文件下載學習示例

2019-11-26 15:33:26
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

package com.hongyuan.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

public class FileDownload {

 public static final String LOCAL_PATH="d:/";

 public static void main(String[] args) {
  //待下載文件地址
  String fileUrl="http://211.162.55.16/cdn.baidupcs.com/file/6a73dab7c03023a9835cc737f447674d?xcode=af6ffdc43a44169bac968d32c4bd420084a9a97c308112c9&fid=3255571826-250528-130564002&time=1397293108&sign=FDTAXER-DCb740ccc5511e5e8fedcff06b081203-mQkOeRDtXpyQWwYJkI%2BxKJpxn5k%3D&to=cb&fm=N,B,U,nc&newver=1&expires=1397297563&rt=sh&r=854979042&logid=1751715936&sh=1&vuk=3255571826&fn=Web%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%20%E7%AC%AC5%E7%89%88.pdf&wshc_tag=0&wsiphost=ipdbm";
  InputStream in=null;
  OutputStream out=null;
  HttpURLConnection conn=null;
  String fileName=null;
  try {
   //初始化連接
   URL url=new URL(fileUrl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setDoInput(true);
   conn.setDoOutput(true);

   //獲取文件名
   String disposition=conn.getHeaderField("Content-Disposition");
   if(disposition!=null&&!"".equals(disposition)){
    //從頭中獲取文件名
    fileName=disposition.split(";")[1].split("=")[1].replaceAll("/"","");
   }else{
    //從地址中獲取文件名
    fileName=fileUrl.substring(fileUrl.lastIndexOf("/")+1);
   }

   if(fileName!=null&&!"".equals(fileName)){
    //文件名解碼
    fileName=URLDecoder.decode(fileName, "utf-8");
   }else{
    //如果無法獲取文件名,則隨機生成一個
    fileName="file_"+(int)(Math.random()*10);
   }

   //讀取數據
   if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
    byte[] buffer=new byte[2048];
    in = conn.getInputStream();
    out=new FileOutputStream(new File(LOCAL_PATH,fileName));
    int count=0;
    int finished=0;
    int size=conn.getContentLength();
    while((count=in.read(buffer))!=-1){
     if(count!=0){
      out.write(buffer,0,count);
      finished+=count;
      System.out.printf("########################################---->%1$.2f%%/n",(double)finished/size*100);
     }else{
      break;
     }
    }
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    out.close();
    in.close();
    conn.disconnect();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南京市| 洛阳市| 海原县| 元氏县| 连山| 青川县| 邛崃市| 新竹县| 贵阳市| 象州县| 邵东县| 会东县| 三原县| 卓资县| 浠水县| 渭南市| 德江县| 高雄县| 民县| 商南县| 乌鲁木齐县| 阿拉善左旗| 安远县| 定结县| 芷江| 淮南市| 台东市| 宝兴县| 江山市| 修水县| 梁平县| 德阳市| 乌苏市| 定安县| 延边| 天津市| 隆化县| 玛纳斯县| 长顺县| 东乌珠穆沁旗| 孝感市|