通过HttpUrlConnection将图片保存到SD中

来源:互联网 发布:java平台发送消息 编辑:程序博客网 时间:2024/05/18 15:07
//由于网络请求属于耗时操作 需要创建线程new Thread(new Runnable() {@Overridepublic void run() {try {//地址URL url = new URL(headImg);//请求方式HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod(“GET”);connection.setConnectTimeout(3000);if (connection.getResponseCode() == 200) {//流InputStream inputStream = connection.getInputStream();//文件名String fileName = “/head.jpg”;//sd路径File path = Environment.getExternalStorageDirectory();//文件路径File file = new File(path.getPath() + fileName);//通过输出流 将流写进sd卡FileOutputStream fileOutputStream = new FileOutputStream(file);                    int num = 0;                    byte[] bytes = new byte[20480];                    //读取流                    while ((num = inputStream.read(bytes)) > 0) {                        //写入                        fileOutputStream.write(bytes, 0, num);                    }                    fileOutputStream.flush();                    fileOutputStream.close();                }            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }    }).start();/** * 获取SD卡中的文件**///文件名String fileName = “/head.jpg”;//路径File path = Environment.getExternalStorageDirectory();//获取SD图片File mFile = new File(path.getPath()+fileName);//若该文件存在if (mFile.exists()) {//将文件直接转换为Bitmap 这样可以直接给ImageViewBitmap bitmap = BitmapFactory.decodeFile(mFile.getPath());        }
原创粉丝点击