从指定网站下载文件

本文介绍了一个线程任务,用于从指定网络地址下载文件并将其保存至手机的SD卡上。

// 创建一个新线程,用于从网络上获取文件

new Thread(new Runnable() {

                    public void run() {
                        try {
                            URL url = new URL(“http://img0.bdstatic.com/img/image/shouye/sheying0717.jpg”); // 创建下载地址对应的URL对象
                            HttpURLConnection urlConn = (HttpURLConnection) url
                                    .openConnection(); // 创建一个连接
                            InputStream is = urlConn.getInputStream(); // 获取输入流对象
                            if (is != null) {
                                String expandName = sourceUrl.substring(
                                        sourceUrl.lastIndexOf(".") + 1,
                                        sourceUrl.length()).toLowerCase(); // 获取文件的扩展名
                                String fileName = sourceUrl.substring(
                                        sourceUrl.lastIndexOf("/") + 1,
                                        sourceUrl.lastIndexOf(".")); // 获取文件名
                                File file = new File("/sdcard/"
                                        + fileName + "." + expandName); // 在SD卡上创建文件
                                FileOutputStream fos = new FileOutputStream(
                                        file); // 创建一个文件输出流对象
                                byte buf[] = new byte[128];// 创建一个字节数组
                                // 读取文件到输出流对象中
                                while (true) {
                                    int numread = is.read(buf);
                                    if (numread <= 0) {
                                        break;
                                    } else {
                                        fos.write(buf, 0, numread);
                                    }
                                }
                            }
                            is.close(); // 关闭输入流对象
                            urlConn.disconnect(); // 关闭连接
                            flag = true;
                        } catch (MalformedURLException e) {
                            e.printStackTrace(); // 输出异常信息
                            flag = false;
                        } catch (IOException e) {
                            e.printStackTrace(); // 输出异常信息
                            String message = e.getMessage();
                            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                            flag = false;
                        }
                        Message m = handler.obtainMessage(); // 获取一个Message
                        handler.sendMessage(m); // 发送消息
                    }
                }).start(); // 开启线程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值