咋下载网上的文件??

来源:互联网 发布:淘宝千禧银楼是真的吗 编辑:程序博客网 时间:2024/06/10 18:33

package test;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadFile {

    public static void getSong(String _path, String _savePath) {
        String savePath = _savePath;
        String path = _path;
        int BYTE_SIZE = 1;
        int SAVE_SIZE = 1024;
        byte[] buff = new byte[BYTE_SIZE]; // 每次读的缓存
        byte[] save = new byte[SAVE_SIZE]; // 保存前缓存
        BufferedInputStream bf = null;
        FileOutputStream file;
        URL url = null;
        HttpURLConnection httpUrl;
        try {
            url = new URL(path);
            httpUrl = (HttpURLConnection) url.openConnection();
            System.out.println("已经打开连接....");
            bf = new BufferedInputStream(httpUrl.getInputStream());
            System.out.println("已经获取资源......");
            file = new FileOutputStream(savePath);
            System.out.println("准备保存到:" + savePath);

            System.out.println("开始读入......");
            int i = 0;
            while (bf.read(buff) != -1) { // 一个字节一个字节读
                save[i] = buff[0];
                if (i == SAVE_SIZE - 1) { // 达到保存长度时开始保存
                    file.write(save, 0, SAVE_SIZE);
                    save = new byte[SAVE_SIZE];
                    i = 0;
                } else {
                    i++;
                }
            }
            // 最后这段如果没达到保存长度,需要把前面的保存下来
            if (i > 0) {
                file.write(save, 0, i - 1);
            }
            System.out.println("下载成功!!!");
            httpUrl.disconnect();
            file.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {

                bf.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            DownloadFile.getSong(
                    "http://wap.sonyericsson.com/UAprof/K700cR201.xml",
                    "D://1.xml");
            DownloadFile.getSong(
                    "http://nds1.nds.nokia.com/uaprof/NN78-1r100.xml",
                    "D://2.xml");
            DownloadFile.getSong("http://www.sohu.com", "D://3.xml");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

原创粉丝点击