从指定服务器地址下载一张图片到SD卡上

来源:互联网 发布:空气曲棍球 淘宝 编辑:程序博客网 时间:2024/05/18 06:19

 //从指定服务器地址下载一张图片到SD卡上
    public void downloadPic(String urladress, String pathstr) {

        HttpConnection conn = null;
        FileConnection fc = null;
        InputStream is = null;
        OutputStream os = null;

        try {
            conn = (HttpConnection) Connector.open(urladress.trim());
            conn.setRequestMethod(HttpConnection.GET);
            fc = (FileConnection) Connector.open("file:///" + pathstr + ".png", Connector.READ_WRITE);

            if (fc.exists()) {
                this.size = fc.fileSize();
            }

            is = conn.openInputStream();
            int ch;
            byte[] b = new byte[1024];

            if (!fc.exists()) {//文件不存在
                fc.create();
                os = fc.openOutputStream();
            } else {//文件已经存在
                fc.truncate(size);
                os = fc.openOutputStream(size);
            }

            while ((ch = is.read(b)) != -1) {
                os.write(b, 0, ch);
            }

            fc.close();
            os.close();
            is.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

原创粉丝点击