咋下载网上的文件??

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();
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值