FileService.java也就是操作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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package com.example.data_storage_sdcard.file;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
import android.os.Environment;
 
/**
 * sdcard的存在于上下文无关
 *
 * @author piaodangdehun
 *
 */
public class FileService {
 
    /*
     * 存放在sdcard的根目录
     */
    public boolean saveFileToSdcardRoot(String fileName, byte[] data) {
        boolean flag = false;
        /*
         * 先判断sdcard的状态,是否存在
         */
        String state = Environment.getExternalStorageState();
        FileOutputStream outputStream = null;
        File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径
        /*
         * 表示sdcard挂载在手机上,并且可以读写
         */
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(rootFile, fileName);
            try {
                outputStream = new FileOutputStream(file);
                try {
                    outputStream.write(data, 0, data.length);
                    flag = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return flag;
    }
 
    /*
     * 存放在sdcard下自定义的目录
     */
    public boolean saveFileToSdcardDir(String fileName, byte[] data) {
        boolean flag = false;
        /*
         * 先判断sdcard的状态,是否存在
         */
        String state = Environment.getExternalStorageState();
        FileOutputStream outputStream = null;
        File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径
        /*
         * 表示sdcard挂载在手机上,并且可以读写
         */
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(rootFile.getAbsoluteFile() + /txt);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                outputStream = new FileOutputStream(new File(file, fileName));
                try {
                    outputStream.write(data, 0, data.length);
                    flag = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return flag;
    }
 
    /*
     * 用于读取sdcard的数据
     */
    public String readContextFromSdcard(String fileName) {
 
        String state = Environment.getExternalStorageState();
        File rooFile = Environment.getExternalStorageDirectory(); // 获得sdcard的目录
 
        FileInputStream inputStream = null;// 用于度取数据的流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 用于存放独处的数据
 
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(rooFile.getAbsoluteFile() + /txt/);// 在sdcard目录下创建一个txt目录
            File file2 = new File(file, fileName);
            int len = 0;
            byte[] data = new byte[1024];
            if (file2.exists()) {
                try {
                    inputStream = new FileInputStream(file2);
                    try {
                        while ((len = inputStream.read(data)) != -1) {
                            outputStream.write(data, 0, data.length);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return new String(outputStream.toByteArray());
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
 
    /**
     * 对文件进行分类的保存到固定的文件中去
     *
     * @param fileName
     * @param data
     */
    public void saveFileToSdcardBySuff(String fileName, byte[] data) {
        // File file = Environment.getExternalStoragePublicDirectory();
        // 保存文件的目录
        File file = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
 
            /*
             * 将不同的文件放入到不同的类别中
             */
            if (fileName.endsWith(.mp3)) {
                file = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
            } else if (fileName.endsWith(.jpg) || fileName.endsWith(.png)
                    || fileName.endsWith(.gif)) {
                file = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            } else if (fileName.endsWith(.mp4) || fileName.endsWith(.avi)
                    || fileName.endsWith(.3gp)) {
                file = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
            } else {
                file = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            }
            FileOutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(new File(file, fileName));
                try {
                    outputStream.write(data, 0, data.length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
 
    /*
     * 删除一个文件
     */
    public boolean deleteFileFromSdcard(String folder, String fileName) {
        boolean flag = false;
        File file = Environment.getExternalStorageDirectory();
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File exitFile = new File(file.getAbsoluteFile() + / + folder);
            if (exitFile.exists()) {
                exitFile.delete();
            }
        }
        return flag;
    }
}

HttpUtils.java访问网络的

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
package com.example.data_storage_sdcard.http;
 
import java.io.IOException;
 
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
 
public class HttpUtils {
    /*
     *
     */
    public static byte[] getImage(String path) {
        byte[] data = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(path);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                data = EntityUtils.toByteArray(response.getEntity());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
 
        return data;
 
    }
}

ImageCache.java将文件放到cache中的:

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
package com.example.data_storage_sdcard.img;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
import android.os.Environment;
 
public class ImageCache {
 
    public static  String saveImageCache(String fileName, byte[] data) {
        File file = Environment.getExternalStorageDirectory(); // 根目录
        FileOutputStream outputStream = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            try {
                outputStream = new FileOutputStream(new File(file, fileName));
                outputStream.write(data, 0, data.length);
 
                return file.getAbsolutePath() + / + fileName;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}

MainActivity.java

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
package com.example.data_storage_sdcard;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
 
import com.example.data_storage_sdcard.http.HttpUtils;
import com.example.data_storage_sdcard.img.ImageCache;
 
public class MainActivity extends Activity {
    private Button button;
    private ImageView imageView;
    private ProgressDialog progressDialog;
 
    private String imageName;
 
    private final String pathString = http://www.baidu.com/img/bd_logo1.png;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) this.findViewById(R.id.button1);
        imageView = (ImageView) this.findViewById(R.id.imageView1);
 
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(下载提示);
        progressDialog.setMessage(load...);
        button.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                new MyTask().execute(pathString);
            }
        });
    }
 
    class MyTask extends AsyncTask<string,> {
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }
 
        @Override
        protected byte[] doInBackground(String... params) {
            String name = params[0];
            imageName = name
                    .substring(name.lastIndexOf(/) + 1, name.length());
            return HttpUtils.getImage(params[0]);
        }
 
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
 
        @Override
        protected void onPostExecute(byte[] result) {
            super.onPostExecute(result);
            if (result != null) {
                Bitmap bm = BitmapFactory.decodeByteArray(result, 0,
                        result.length);
                imageView.setImageBitmap(bm);
                ImageCache.saveImageCache(, result);
            } else {
                imageView.setImageResource(R.drawable.ic_launcher);
            }
            progressDialog.dismiss();
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
}
</string,>

测试类:

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
package com.example.data_storage_sdcard;
 
import java.io.FileWriter;
 
import com.example.data_storage_sdcard.file.FileService;
 
import android.nfc.Tag;
import android.test.AndroidTestCase;
import android.util.Log;
 
public class MyTest extends AndroidTestCase {
 
    public void saveFileToSdcardTest() {
        FileService fileService = new FileService();
 
        fileService.saveFileToSdcardRoot(aa.txt,
                jkhdsfjkhdskjfhdsjf.getBytes());
    }
 
    public void saveFileToSdcardDir() {
        FileService fileService = new FileService();
 
        fileService.saveFileToSdcardRoot(aa.txt,
                jkhdsfjkhdskjfhdsjf.getBytes());
    }
 
    public void readContextFromSdcardTest() {
        FileService fileService = new FileService();
        String msg = fileService.readContextFromSdcard(aa.txt);
        System.err.println(--> + msg);
    }
 
    public void saveFileToSdcardBySuffTest() {
        FileService fileService = new FileService();
        fileService.saveFileToSdcardBySuff(aa.avi,
                asdfkajsgdhagsdfhdgsf.getBytes());
    }
 
    public void delFile() {
        FileService fileService = new FileService();
        boolean flag = fileService.deleteFileFromSdcard(txt, aa.txt);
    }
}

需要在请单位按中加入访问网络的权限、操作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
<!--?xml version=1.0 encoding=utf-8?-->
<manifest android:versioncode="1" android:versionname="1.0" package="com.example.data_storage_sdcard" xmlns:android="http://schemas.android.com/apk/res/android">
 
    <uses-sdk android:minsdkversion="8" android:targetsdkversion="18">
 
    <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetpackage="com.example.data_storage_sdcard">
    </instrumentation>
    <!-- 添加访问sdcard的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
    <!-- 添加访问网络的权限 -->
    <uses-permission android:name="android.permission.INTERNET">
 
     
        <uses-library android:name="android.test.runner">
 
         
            <intent-filter>
                 
 
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
 
        <uses-library>
        </uses-library>
    </uses-library></application>
 
</uses-permission></uses-permission></uses-sdk></manifest>
 

结伴旅游,一个免费的交友网站:www.jieberu.com

推推族,免费得门票,游景区:www.tuituizu.com

Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类的更多相关文章

  1. 【转】 Pro Android学习笔记(九二):AsyncTask(1):AsyncTask类

    文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn.net/flowingflying/ 在Handler的学习系列中,学习了如何h ...

  2. Android 学习笔记之数据存储SharePreferenced+File

    学习内容: Android的数据存储.... 1.使用SharedPreferences来保存和读取数据... 2.使用File中的I/O来完成对数据的存储和读取...   一个应用程序,经常需要与用 ...

  3. Android学习笔记——保存数据到SQL数据库中(Saving Data in SQL Databases)

    知识点: 1.使用SQL Helper创建数据库 2.数据的增删查改(PRDU:Put.Read.Delete.Update) 背景知识: 上篇文章学习了保存文件,今天学习的是保存数据到SQL数据库中 ...

  4. Android学习笔记-保存数据的实现方法1

    Android开发中,有时候我们需要对信息进行保存,那么今天就来介绍一下,保存文件到内存,以及SD卡的一些操作,及方法,供参考. 第一种,保存数据到内存中: //java开发中的保存数据的方式 pub ...

  5. Android学习笔记_36_ListView数据异步加载与AsyncTask

    一.界面布局文件: 1.加入sdcard写入和网络权限: <!-- 访问internet权限 --> <uses-permission android:name="andr ...

  6. Android学习笔记-保存数据的实现方法2-SharedPreferences

    Android下,数据的保存,前面介绍过了,把数据保存到内存以及SD卡上,这次我们就介绍一下,更为常用的采用SharedPreferences的方式来保存数据, 1,得到SharedPreferenc ...

  7. python学习笔记3_数据载入、存储及文件格式

    一.丛mysql数据库中读取数据 import pandas as pdimport pymysqlconn = pymysql.connect( host = '***', user = '***' ...

  8. [Android学习笔记]子线程更新UI线程方法之Handler

    关于此笔记 不讨论: 1.不讨论Handler实现细节 2.不讨论android线程派发细节 讨论: 子线程如何简单的使用Handler更新UI 问题: android开发时,如何在子线程更新UI? ...

  9. Android学习笔记——log无法输出的解决方法和命令行查看log日志

    本人邮箱:JohnTsai.Work@gmail.com,欢迎交流讨论. 欢迎转载,转载请注明网址:http://www.cnblogs.com/JohnTsai/p/3983936.html. 知识 ...

随机推荐

  1. Oozie 3.3.1安装

    软件安装路径 软件名称 版本 安装路径 jdk 1.6.0_12 /usr/java/jdk1.6.0_12 maven 3.1.0 /usr/local//apache-maven-3.1.0 Oo ...

  2. java方法形参是引用类型

    public void 方法名(Student s) 这里形参需要的是该类的对象或者子类对象(父类引用子类对象). 1.若为普通类:则可传入该类的实例对象即可,方法名(new Student()): ...

  3. 异步任务报错-Celery: WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL)

    现象: 异步任务: 测试环境正常,线上环境报错 使用celery 进行后端异步任务时,报错: Celery: WorkerLostError: Worker exited prematurely: s ...

  4. 细说vue axios登录请求拦截器

    当我们在做接口请求时,比如判断登录超时时候,通常是接口返回一个特定的错误码,那如果我们每个接口都去判断一个耗时耗力,这个时候我们可以用拦截器去进行统一的http请求拦截. 1.安装配置axios cn ...

  5. day 01 常量 注释 int(整型) 用户交互input 流程控制语句if

    python的编程语言分类(重点) if 3 > 2: 编译型: 将代码一次性全部编译成二进制,然后再执行. 优点:执行效率高. 缺点:开发效率低,不能跨平台. 代表语言:C 解释型: 逐行解释 ...

  6. Linux端口是否占用的方法

    1.netstat或ss命令 netstat -anlp | grep 80 2.lsof命令 这个命令是查看进程占用哪些文件的 lsof -i:80 3.fuser命令 fuser命令和lsof正好 ...

  7. Android 之 悬浮窗口

    1. 创建并设置  WindowManager  类 WindowManager mWindowManager; // 取得系统窗体 mWindowManager = (WindowManager) ...

  8. .Net Core 认证系统源码解析

    不知不觉.Net Core已经推出到3.1了,大多数以.Net为技术栈的公司也开始逐步的切换到了Core,从业也快3年多了,一直坚持着.不管环境怎么变,坚持自己的当初的选择,坚持信仰 .Net Cor ...

  9. 手把手教你如何安装使用webpack vue cli

    1.安装node.js:https://nodejs.org/en/download/(看电脑的系统是多少位下载相应版本) 我下载的是Windows Installer(.msi) x64 2.打开c ...

  10. CSS高度坍塌问题的原因以及解决办法

    原因: 在文档流中,父元素的高度默认是被子元素撑开的,也就是子元素多高,父元素就多高.但是当为子元素设置浮动以后,子元素会完全脱离文档流,此时将会导致子元素无法撑起父元素的高度,导致父元素的高度塌陷. ...