【Android】网络下载图片&SD卡文件存储

(本博客的作用:可以使用源码在虚拟机里面的SD卡上添加图片(找到URL即可),可以用来操作SD卡上的文件)

以下是一个从网络下载图片的函数,放入URL即可: 

 1 public Bitmap returnBitMap(String url) {   
 2            URL myFileUrl = null;   
 3            Bitmap bitmap = null;   
 4            try {   
 5             myFileUrl = new URL(url);   
 6            } catch (MalformedURLException e) {   
 7             e.printStackTrace();   
 8            }   
 9            try {   
10             HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();   
11             conn.setDoInput(true);   
12             conn.connect();   
13             InputStream is = conn.getInputStream();   
14             bitmap = BitmapFactory.decodeStream(is);  
15             is.close();   
16            } catch (IOException e) {   
17             e.printStackTrace();   
18            }  
19            if(bitmap == null){
20             Log.d("RRRyy", "Null");
21            }
22            
23            return bitmap;   
24         } 

比如传入:"http://pica.nipic.com/2008-04-01/200841194113617_2.jpg",返回的是bitmap

 

下面是一个传入bitmap和文件名(文件名要有扩展名),将图片存入SD卡的类:

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 import android.graphics.Bitmap;
 7 import android.os.Environment;
 8 import android.util.Log;
 9 
10 /**
11 * 保存图片的类
12 * 
13 * @author Administrator
14 * 
15 */
16 public class PicSave {
17 
18         private final static String CACHE = "/Caochen";//存储的文件夹
19 
20         /**
21          * 保存图片的方法
22          * 保存到sdcard
23          * @throws IOException
24          */
25         public void savePic(Bitmap b, String strFileName) {30                 String filePath = isExistsFilePath();
31                 FileOutputStream fos = null;//流
32                 File file = new File(filePath, strFileName);
33                 if (file.exists()) {//如果存在,未处理
34                 } else {
35                         try {
36                                 fos = new FileOutputStream(file);
37                                 if (null != fos) {
38                                         b.compress(Bitmap.CompressFormat.JPEG, 90, fos);//格式
39                                         fos.flush();
40                                         fos.close();
41                                         Log.d("YYHU", "ok");
42                                 }
43                         } catch (FileNotFoundException e) {
44                                 e.printStackTrace();
45                         } catch (IOException e) {
46                                 e.printStackTrace();
47                         }
48                 }
49         }
50 
51         /**
52          * 获取sd卡的缓存路径, 
53          * 一般在卡中sdCard就是这个目录
54          * 
55          * @return SDPath
56          */
57         public static String getSDPath() {
58                 File sdDir = null;
59                 boolean sdCardExist = Environment.getExternalStorageState().equals(
60                                 android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
61                 if (sdCardExist) {
62                         sdDir = Environment.getExternalStorageDirectory();// 获取根目录
63                 } else {
64                         Log.e("ERROR", "没有内存卡");
65                 }
66                 return sdDir.toString();
68         }
69 
70         /**
71          * 获取缓存文件夹目录 如果不存在创建 否则则创建文件夹
72          * 
73          * @return filePath
74          */
75         private String isExistsFilePath() {
76                 String filePath = getSDPath()+CACHE;
77                 File file = new File(filePath);
78                 if (!file.exists()) {
79                         file.mkdirs();//建立文件夹
80                 }
81                 return filePath;
82         }
84 }

记住,为了正确运行上面两个类,一定要添加下面的权限:

1 <!-- 在SDCard中创建与删除文件权限 -->
2 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
3 <!-- 往SDCard写入数据权限 -->
4 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
5 <uses-permission android:name="android.permission.INTERNET"/>

 

为了更加清楚的知道SD卡文件夹的操作,我在源代码中加入如下输出:

 1 /**
 2          * 获取sd卡的缓存路径, 
 3          * 一般在卡中sdCard就是这个目录
 4          * 
 5          * @return SDPath
 6          */
 7         public static String getSDPath() {
 8                 File sdDir = null;
 9                 boolean sdCardExist = Environment.getExternalStorageState().equals(
10                                 android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
11                 if (sdCardExist) {
12                         sdDir = Environment.getExternalStorageDirectory();// 获取根目录
13                 } else {
14                         Log.e("ERROR", "没有内存卡");
15                 }
16                 Log.d("a", sdDir.getAbsolutePath());//  /mnt/sdcard
17                 Log.d("b", sdDir.toString());//      /mnt/sdcard
18                 Log.d("c", sdDir.getPath());//       /mnt/sdcard
19                 Log.d("d", sdDir.getParent());//      /mnt
20                 Log.d("e", sdDir.getName());//       sdcard22                 Log.d("g", sdDir.toURI() + "");//     file:/mnt/sdcard
23                 return sdDir.toString();
24 
25         }

输出如注释所示!

下面为了更好的理解,贴出在SD卡中寻找所有图片的代码:输入为根目录,比如:/mnt/sdcard

 1 import java.io.File;
 2 import java.util.ArrayList;
 3 
 4 import android.util.Log;
 5 
 6 public class PicDir {
 7     
 8     public void getFileDir(String opath){
 9           File f = new File(opath);
10           File[] files = f.listFiles();
11           if (files != null) {
12           int count = files.length;       
13           for (int i = 0; i < count; i++){
14                File file = files[i];
15                String filepath = file.getAbsolutePath();
16                String path = file.getPath();
17                  
18                if (filepath.endsWith("jpg") || filepath.endsWith("gif")|| filepath.endsWith("bmp")
19                                             || filepath.endsWith("png")) {
20                  
21                  ArrayList<String> myFilePath=new ArrayList<String>();
22                  myFilePath.add(filepath);//这里每次扫描目录都会添加。
23                  
24                  for (String ll : myFilePath) {
25                          Log.e("myFilePath", ll.toString());
26                  }
27            }
28            else{ // 目标为文件夹,进入该文件夹继续遍历
29                        if (file.isDirectory()) {
30                            this.getFileDir(path);
31                  }
32                }
33                continue;
34               }
35         }
36     }
37 }
posted @ 2012-09-19 23:44  大脚印  阅读(1081)  评论(0编辑  收藏  举报