外部存储(SD卡) External Storage
1, 特点
1, 插入sd卡
2, 分为两部分: sd的公共目录 sd的私有目录
3, 公共目录下的文件可以被应用程序共享, 私有目录下的文件只能被当前应用程序访问
4, 当程序卸载后, 公共目录下的文件不会被清除, 私有目录下的文件会被清除
2, 路径
mnt/sdcard 4.0版本之前的目录
storage/sdcard 4.0后的目录 公共目录
storage/sdcard/Android/data/应用程序包名/... 私有目录
3, 读写sd卡的权限
WRITE_EXTERNAL_STORAGE 写sd卡的权限
READ_EXTERNAL_STOAGE 读sd卡的权限
4, 获取扩展卡的根目录
Environment.getExternalStorageDirectory()
5, 获取当前扩展卡的状态
Environment.getExternalStorageState()
MEDIA_MOUNTED 挂载的状态, sd卡已经被装载并且可以使用, 判断存储的状态符合该条件, 则能进行存取文件
6, 目录
context.getExternalFilesDir(null) 私有目录的根目录
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOAD) 私有目录中的download目录中
context.getExternalCacheDir() 私有目录中的缓存目录
Environment.getExternalStorageDirectory() sd卡的根目录
1, 特点
1, 插入sd卡
2, 分为两部分: sd的公共目录 sd的私有目录
3, 公共目录下的文件可以被应用程序共享, 私有目录下的文件只能被当前应用程序访问
4, 当程序卸载后, 公共目录下的文件不会被清除, 私有目录下的文件会被清除
2, 路径
mnt/sdcard 4.0版本之前的目录
storage/sdcard 4.0后的目录 公共目录
storage/sdcard/Android/data/应用程序包名/... 私有目录
3, 读写sd卡的权限
WRITE_EXTERNAL_STORAGE 写sd卡的权限
READ_EXTERNAL_STOAGE 读sd卡的权限
4, 获取扩展卡的根目录
Environment.getExternalStorageDirectory()
5, 获取当前扩展卡的状态
Environment.getExternalStorageState()
MEDIA_MOUNTED 挂载的状态, sd卡已经被装载并且可以使用, 判断存储的状态符合该条件, 则能进行存取文件
6, 目录
context.getExternalFilesDir(null) 私有目录的根目录
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOAD) 私有目录中的download目录中
context.getExternalCacheDir() 私有目录中的缓存目录
Environment.getExternalStorageDirectory() sd卡的根目录
Environment.getExternalStorageDirectory(Environment.DIRECTORY_DOWNLOAD) 公共目录中的download目录中
<pre name="code" class="java">package com.qf.day12_storage_external;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.qf.day12_storage_external.tools.HttpUtils;
import com.qf.day12_storage_external.tools.SDCardUtils;
public class MainActivity extends Activity {
private ImageView iv;
private String path = "http://img5.duitang.com/uploads/blog/201602/21/20160221193234_EtLYz.jpeg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
}
public void downLoad(View v)
{
//如果sd卡中有图片, 则取出并显示
Bitmap bitmap = SDCardUtils.getBitmap(path);
if(bitmap!=null)
{
iv.setImageBitmap(bitmap);
}
else
{
//如果sd卡中没有图片, 开启异步任务下载图片, 并且将下载好的图片存入sd卡中
new MyTask().execute(path);
}
}
public void show(View v)
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
/**
* 自定义 异步任务 下载图片
* @author Administrator
*
*/
public class MyTask extends AsyncTask<String, Void, Bitmap>
{
@Override
protected Bitmap doInBackground(String... params) {
// TODO 下载图片
byte[] data = HttpUtils.getByteResult(params[0]);
if(data!=null && data.length>0)
{
//将下载好的图片, 存入sd卡中
SDCardUtils.saveImg(params[0], data);
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO 更新UI
super.onPostExecute(result);
if(result!=null)
{
iv.setImageBitmap(result);
Toast.makeText(MainActivity.this, "图片下载成功!!", Toast.LENGTH_SHORT).show();
}else Toast.makeText(MainActivity.this, "数据加载失败,请稍后再试...", Toast.LENGTH_SHORT).show();
}
}
}
package com.qf.day12_storage_external;
import com.qf.day12_storage_external.tools.SDCardUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class SecondActivity extends Activity {
private EditText nameEdit,contentEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
nameEdit = (EditText) findViewById(R.id.file_name);
contentEdit = (EditText) findViewById(R.id.content_id);
}
//保存
public void save(View v)
{
//得到输入框的内容
String fileName = nameEdit.getText().toString().trim();
String content = contentEdit.getText().toString().trim();
//向sd卡的私有目录中存入数据
SDCardUtils.savePrivate(this,fileName,content);
}
//打开
public void open(View v)
{
String fileName = nameEdit.getText().toString().trim();
//根据名称 从sd卡的私有目录中得到内容
String content = SDCardUtils.open(this,fileName);
contentEdit.setText(content);
}
}
package com.qf.day12_storage_external.tools;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* Http 加载网络数据
* @author Administrator
*
*/
public class HttpUtils {
/**
* 加载网络数据
* @param path 路径
* @return String
*/
public static String getStringResult(String path) {
HttpURLConnection conn = null;
InputStream is = null;
try {
//1, 得到URL 对象
URL url = new URL(path);
//2, 打开连接
conn = (HttpURLConnection) url.openConnection();
//3, 设置请求方式
conn.setRequestMethod("GET");
//4, 连接
conn.connect();
//5, 判断返回的结果码 (200),得到响应数据
if(conn.getResponseCode() == 200)
{
is = conn.getInputStream();
StringBuilder sBuilder = new StringBuilder();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer))!=-1) {
sBuilder.append(new String(buffer,0,len));
}
return sBuilder.toString();
}
} catch (Exception e) {
e.printStackTrace();
}finally
{
if(conn!=null)
{
conn.disconnect();
}
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/**
* 加载网络图片
* @param path
* @return byte[]
*/
public static byte[] getByteResult(String path)
{
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1, 得到URL 对象
URL url = new URL(path);
//2, 打开连接
conn = (HttpURLConnection) url.openConnection();
//3, 设置请求方式
conn.setRequestMethod("GET");
//4, 连接
conn.connect();
//5, 判断返回的结果码 (200),得到响应数据
if(conn.getResponseCode() == 200)
{
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len=is.read(buffer))!=-1) {
baos.write(buffer, 0, len);
baos.flush();
}
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}finally
{
if(conn!=null)
{
conn.disconnect();
}
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(baos!=null)
{
try {
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
}
package com.qf.day12_storage_external.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
/**
* sd 卡的存储
* @author Administrator
*
*/
public class SDCardUtils {
//保存图片的目录
//private static final String PATH = Environment.getExternalStorageDirectory()+"/1614/img/";
private static final String PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+File.separator;
/**
* 判断当前的sd卡是否可用
*
* MEDIA_MOUNTED SD的可用状态
* @return
*/
public static boolean isMounted()
{
//1, 得到当前sd的状态
String state = Environment.getExternalStorageState();
//2, 跟系统提供的挂载状态比较
return state.equals(Environment.MEDIA_MOUNTED);
}
/**
* 从图片路径中, 获取图片的名称
* @param path
* @return
*/
public static String getFileName(String path)
{
return path.substring(path.lastIndexOf("/")+1);
}
/**
* 保存图片到sd卡的公共目录中
* @param path 图片的路径 (截取图片名称)
* @param data 图片内容
* @throws Exception
*/
public static void saveImg(String path,byte[] data)
{
FileOutputStream fos = null;
try {
//1, 判断当前的sd卡是否可用
if(!isMounted()) return;
//2, 判断当前缓存的目录是否存在, 如果不存在 级联创建
File dir = new File(PATH);
if(!dir.exists())
{
dir.mkdirs();//级联创建
}
//3, 将图片的字节,写入到指定的文件中
fos = new FileOutputStream(new File(dir, getFileName(path)));
fos.write(data);
} catch (Exception e) {
e.printStackTrace();
}finally
{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 根据图片的名称, 从sd卡的公共目录中, 读取图片内容
* @param path
* @return
*/
public static Bitmap getBitmap(String path)
{
if(!isMounted()) return null;
File file = new File(PATH, getFileName(path));
if(file.exists())
{
//把绝对路径中的图片 转成Bitmap格式
return BitmapFactory.decodeFile(file.getAbsolutePath());
}
return null;
}
/**
* 向Sd卡的私有目录中写入内容
* @param fileName
* @param content
*/
public static void savePrivate(Context context,String fileName, String content) {
//判断sd卡的状态是否可用
if(!isMounted()) return;
//Sd卡的私有根目录 context.getExternalFilesDir(null)
//context.getExternalCacheDir() 缓存中
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
finally
{
if(fos!=null)
{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 根据文件名称 读取外部存储私有目录中的文件内容
* @param context
* @param fileName
* @return
*/
public static String open(Context context, String fileName) {
String result = null;
if(!isMounted()) return result;
//创建外边存储的文件对象
//context.getExternalCacheDir() 缓存中
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName);
FileInputStream fis = null;
BufferedReader reader = null;
StringBuilder sBuilder = new StringBuilder();
try {
fis = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line= reader.readLine())!=null) {
sBuilder.append(line);
}
result = sBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fis!=null)
{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(reader!=null)
{
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
//----------------------
/**
* 清除sd卡指定目录中的数据
*/
public static void clearCaches()
{
if(!isMounted()) return ;
//得到缓存目录中的文件
File file = new File(PATH);
if(file.exists())
{
//列出指定目录中的所有文件
File[] files = file.listFiles();
for(File fl: files)
{
fl.delete();//删除文件
}
}
}
/**
* 判断sd卡的可用空间
*/
public static boolean isAvailable()
{
if(!isMounted()) return false;
//1, 实例化文件管理系统的状态对象 StatFs
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
long size = 0; //字节
if(Build.VERSION.SDK_INT >=18)
{
size = statFs.getFreeBytes();
}else
{
//可用的代码块 * 每个块的大小
size = statFs.getFreeBlocks() * statFs.getBlockSize();
}
//可用空间必须大于10M , 则表示可以使用
if(size > 10*1024*1024)
{
return true;
}
return false;
}
}