通过url下载文件到本地

1:通过URL下载文件:
public class DownFile {
 /**
  * @param args
  * @throws Exception 
  */
 public static void main(String[] args) throws Exception {
  String encodedStr = java.net.URLEncoder.encode("我是中文","GBK"); // 有时用UTF-8
  download("http://www.baidu.com?args=" + encodedStr,"c:\\ret.html");
  download("http://music.yule.sohu.com/upload/zhiqianqiutian.mp3", "C:\\1.mp3");
 }
 public static void download(String urlString,String filename)throws Exception{
  URL url = new URL(urlString);
  URLConnection con = url.openConnection();
  InputStream is = con.getInputStream();
  
  byte[] bs = new byte[1024];
  int len;
  OutputStream os = new FileOutputStream(filename);
  while((len = is.read(bs))!=-1){
   os.write(bs, 0, len);
  }
  os.close();
  is.close();
 }
}

2:缓冲读取URL方法:
package com.rayoo.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class TestDownFile {

    public static void main(String[] args) throws Exception {
        java.net.URLDecoder.decode(java.net.URLEncoder.encode("我是中文", "GBK"), "GBK");
        download("http://music.yule.sohu.com/upload/zhiqianqiutian.mp3", "C:\\1.mp3");
    }

    public static void download(String urlString, String filename)
            throws Exception {
        URL url = new URL(urlString);
        URLConnection con = url.openConnection();
        InputStream is = con.getInputStream();
        OutputStream os = new FileOutputStream(filename);

        BufferedInputStream bufferInput = new BufferedInputStream(is);
        BufferedOutputStream bufferOutput = new BufferedOutputStream(os);

        byte[] bs = new byte[1024];
        int len = 0;
        while ((len = bufferInput.read(bs)) != -1) {
            bufferOutput.write(bs, 0, len);
        }

        bufferOutput.flush();

        bufferInput.close();
        bufferOutput.close();
        os.close();
        is.close();
    }

}

-----------------------------------------------------------
URL url = new URL("http://www.baidu.com");

InputStream is = url.openStream();

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) >= 0) {
	byteArrayOutputStream.write(bytes, 0, read);
}

File file = new File("c:\\test.txt");
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
if(!file.exists())
file.createNewFile();

FileOutputStream fos = new FileOutputStream(file);
fos.write(byteArrayOutputStream.toByteArray());

is.close();
fos.close();

你可能感兴趣的:(下载文件)