Andriod- 从网络下载文件保存到SDCARD里

如何从网络下载图片保存到SDCARD里面,直接看代码,这个通用,应该可以应用成从网络下载文件保存到SDCARD内。

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.cts.testdwonloadimage.testdwonloadimage;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class MainActivity extends AppCompatActivity {
 
    private ImageView mImageView;
    private File cache;
    private String imgPath="https://www.cnblogs.com/images/logo_small.gif";
 
 
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //显示
            Bitmap b=(Bitmap)msg.obj;
            mImageView.setImageBitmap(b);
            //保存至本地
            File imgFile=new File(cache,"woca.jpg");
            try {
                BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(imgFile));
                b.compress(Bitmap.CompressFormat.JPEG,80,bos);
                bos.flush();
                bos.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return false;
        }
    });
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mImageView=(ImageView)findViewById(R.id.mImageView);
 
        cache=new File(Environment.getExternalStorageDirectory(),"Test");
        if(!cache.exists()){
            cache.mkdirs();
        }
 
        new Thread(){
            @Override
            public void run() {
                super.run();
 
                HttpURLConnection conn = null;
                InputStream is = null;
 
                try{
                    URL url = new URL(imgPath);
                    conn=(HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    if(conn.getResponseCode()==200){
                        is=conn.getInputStream();
                        Bitmap b= BitmapFactory.decodeStream(is);
                        //把输入流转化成bitmap格式,以msg形式发送至主线程
                        Message msg=new Message();
                        msg.obj=b;
                        handler.sendMessage(msg);
                    }
 
                }catch (Exception e){
 
                    String strEx = e.getMessage();
                    strEx = strEx + "111";
                }finally {
                    //conn.disconnect();
                }
 
            }
        }.start();
 
    }
}

 

下载文件进一步

复制代码
package com.cts.testdwonloadimage.testdwonloadimage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private ImageView mImageView;
    private File cache;
    private String imgPath = "https://www.cnblogs.com/images/logo_small.gif";
    private PrintStream ps = null;
    private FileOutputStream os = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnTest = findViewById(R.id.btnTest);
        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnTest();
            }
        });
    }


    public void btnTest() {
        cache = new File(Environment.getExternalStorageDirectory(), "Test");
        if (!cache.exists()) {
            cache.mkdirs();
        }

        new Thread() {
            @Override
            public void run() {
                super.run();

                HttpURLConnection conn = null;
                InputStream is = null;

                try {
                    URL url = new URL(imgPath);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200) {
                        is = conn.getInputStream();

                        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();
                            return;
                        }

                        /*
                        Bitmap b= BitmapFactory.decodeStream(is);
                        //把输入流转化成bitmap格式,以msg形式发送至主线程
                        Message msg=new Message();
                        msg.obj=b;
                        handler.sendMessage(msg);
                        */

                        //初始化File
                        String FILENAME = "logo_smallaaa.gif";
                        String path = Environment.getExternalStorageDirectory().toString()
                                + File.separator
                                + "genwoxue"
                                + File.separator
                                + FILENAME;
                        File file = new File(path);

                        if (!file.getParentFile().exists())
                            file.getParentFile().mkdirs();


                        //ps = new PrintStream(new FileOutputStream(file));
                        os = new FileOutputStream(path);

                        byte[] buff = new byte[1024];
                        int hasRead = 0;
                        while ((hasRead = is.read(buff)) > 0) {
                            os.write(buff);
                        }


                    }

                } catch (Exception e) {

                    String strEx = e.getMessage();
                    strEx = strEx + "111";
                } finally {
                    //conn.disconnect();
                }

            }
        }.start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_LONG).show();
    }

}
复制代码

 

posted @   春天又来了  阅读(178)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示