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

原创文章 47 获赞 34 访问量 3万+

猜你喜欢

转载自blog.csdn.net/xige1995/article/details/79567376