zoukankan      html  css  js  c++  java
  • 下载文件到某个路径

    /**
    	 * 下载文件到某个路径
    	 * @param url
    	 * @param path
    	 */
        public static long downloadFile(String url,String path){
        	StringBuffer sb = new StringBuffer();
        	
        	
        	PrintWriter out = null;
        	InputStream in = null;
        	FileOutputStream os = null;
        	try {
                 URL realUrl = new URL(url);
                 // 打开和URL之间的连接
                 URLConnection conn = realUrl.openConnection();
                 // 设置通用的请求属性
                 conn.setRequestProperty("accept", "*/*");
                 conn.setRequestProperty("connection", "Keep-Alive");
    //             if(StringUtils.isNotBlank(serverCode)){
    //             	long time = System.currentTimeMillis();
    //             	StringBuilder bd = new StringBuilder().append(serverCode).append(time).append(secret);
    //             	String md5 = "";
    //             	try {
    //             		md5 = SecretFactory.getInstance().getSecret(SecretType.MD5).encode(bd.toString());
    //             	} catch (SecretException e1) {
    //             		e1.printStackTrace();
    //             	}
    //         	
    //             	String auth = serverCode + ";" + time + ";" + md5;
    //             	conn.setRequestProperty("Authorization", auth);
    //             }
                 conn.setRequestProperty("user-agent",
                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                 // 发送POST请求必须设置如下两行
                 conn.setDoOutput(true);
                 conn.setDoInput(true);
                 out = new PrintWriter(conn.getOutputStream());
                 out.print(sb.toString());
                 // flush输出流的缓冲
                 out.flush();
                 // 定义InputStream输入流来读取URL的响应
                 in = conn.getInputStream();
                 os = new FileOutputStream(path); 
                 byte[] buffer = new byte[4*1024]; 
                 int read; 
                 long size = 0;
                 while((read = in.read(buffer)) > 0){ 
                	 os.write(buffer, 0, read); 
                	 size+=read;
                 } 
                 return size;
        	}catch(Exception e){
        		e.printStackTrace();
        		return 0;
        	}finally{
        		out.close();
        		try {
    				in.close();
    			} catch (IOException e1) {
    				e1.printStackTrace();
    			}
        		try {
    				os.close();
    			} catch (IOException e1) {
    				e1.printStackTrace();
    			}
        	}
        	
        	
        }
    

      

  • 相关阅读:
    [JLOI2015] 管道连接
    【知识点】斯坦纳树
    [ZJOI2010] 网络扩容
    【知识点】网络流常见模型
    [NOI2009] 植物大战僵尸
    [NOI2007] 货币兑换
    【知识点】分治相关算法
    [NOI2005] 月下柠檬树
    [HNOI2012] 射箭
    [SDOI2014] 向量集
  • 原文地址:https://www.cnblogs.com/lishupeng/p/6722979.html
Copyright © 2011-2022 走看看