Android下载网络资源文件

直接上代码:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
new Thread(new Runnable() {
    @Override
    public void run() {
        download();
    }
}).start();
//下载具体操作
private boolean download() {
    try {
        URL url = new URL("http://file.chmsp.com.cn/colligate/file/00100000224821.pdf");
        //打开连接
        URLConnection conn = url.openConnection();
        //打开输入流
        InputStream is = conn.getInputStream();
        //获得长度
        int contentLength = conn.getContentLength();
        Log.e("", "文件长度 = " + contentLength);
        //创建文件夹 MyDownLoad,在存储卡下
        String dirName = Environment.getExternalStorageDirectory() + "/";
        //下载后的文件名
        String fileName = dirName + "00100000224821.pdf";
        File file1 = new File(fileName);

        if (file1.exists()) {
            Log.e("文件-----", "文件已经存在!");
            return fileIsExists(fileName);
        } else {
            //创建字节流
            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(fileName);
            //写数据
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            //完成后关闭流
            Log.e("文件不存在", "下载成功!");
            os.close();
            is.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

//判断文件是否存在
public boolean fileIsExists(String strFile) {
    try {
        File f = new File(strFile);
        if (!f.exists()) {
            return false;
        }

    } catch (Exception e) {
        return false;
    }

    return true;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值