Android 官方 Api:每个兼容 Android 的设备都支持可用于保存文件的共享 “外部存储”。 该存储可能是可移除的存储介质(例如 SD 卡)或内部(不可移除)存储。 保存到外部存储的文件是全局可读取文件,而且,在计算机上启用 USB 大容量存储以传输文件后,可由用户修改这些文件。
详解: 外部存储中的文件可以被用户或者其他应用程序读写的,其中有两种类型的文件。
(1). 公共文件 public fies 这类文件可被自由访问,当应用被卸载之后,文件仍然保留。比如相机类应用被卸载后,照片仍然存在。公共文件有 9 大类,均为系统创建的文件夹,
详细如下: 文件夹类型包括:
- DCIM : 数字相机拍摄的照片
- Music:用户音乐
- Podcasts:音频 / 视频的剪辑片段
- Ringtones:铃声
- Alarms:闹钟的声音
- Notification:通知
- Pictures:所有的图片 (不包括那些用照相机拍摄的照片)
- Movies:所有的电影 (不包括那些用摄像机拍摄的视频) 和 Download / 其他下载的内容。
使用外部存储数据需要在应用程序中设置访问 SD 卡的权限,在 AndroidManifest.xml 中添加权限
<!-- 在sd卡中创建和删除文件权限-->
<uses-permission android:/>
<!-- 往sd卡写入数据权限-->
<uses-permission android:/>
<!-- 从sd卡读取数据权限-->
<uses-permission android:/>
首先判断是否存在可用的 SD 卡,Environment.getExternalStorageState() 方法获取当前设备的状
态,判断是否为 Environment.MEDIA_MOUNTED 状态。
//判断SD卡是否存在
if(Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)){
//记得最后要调用保存文件的方法实现保存
Toast.makeText(getApplicationContext(),"sd卡存在",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "sd卡不存在", Toast.LENGTH_LONG).show();
}
存储的文件路径使用 Environment.getExternalStorageDirectory() 方法获取当 SD 卡的根目录,进而访问相应的文件。创建公有文件的方法 :
File file=new File(Environment.getExternalStorageDirectory(),“boreseven”);
第二个参数为自己设置的名字
(2). 私有文件 Private files 在应用被卸载后,私有文件也会被删除,类似与内部储存。获得外部储存私有文件路径的方法 Context.getExternalFilesDir(),如: 如:File file = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), “boreseven”);**
下面小提一下两个方法:
- 保存文件到 SD 卡:
//保存文件到SD卡
public void saveToSDCard(String filename,String content){
File file=new File(Environment.getExternalStorageDirectory(),filename);
try {
FileOutputStream outputStream=new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
- 读取 SD 卡文件:
//读取SD卡文件
public String readFileSdcard(String filename){
String res="";
try {
FileInputStream myfin=new FileInputStream(filename);
int length=myfin.available();
byte [] buff=new byte[length];
myfin.read(buff);
res= new String(buff, "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
拓展:点击按钮下载图片,可在系统相册中显示。
记得要添加权限,代码如下:
xml 文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
<Button
android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="保存" />
</RelativeLayout>
java 文件:
public class MainActivity extends Activity {
private ImageView imageView;
private Button mybutton;
private Handler handler;
private String URL="https://www.baidu.com/img/bd_logo1.png";//百度首页图片地址
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case 1://成功
byte[]result= (byte[]) msg.obj;
final Bitmap bitmap=BitmapFactory.decodeByteArray(result,0,result.length);//利用BitmapFactory将数据转换成bitmap类型
imageView.setImageBitmap(bitmap);//加载图片
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
saveImageToGallery(MainActivity.this,bitmap);
return false;
}
});
}
return false;
}
});
OkHttpClient client=new OkHttpClient();//实例化
final Request request = new Request.Builder().url(URL).build(); //传入图片网址,,URL为自己定义好的网址。
client.newCall(request).enqueue(new Callback() {//实例化一个call的对象
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message=handler.obtainMessage();//声明一个传递信息的Message
if (response.isSuccessful()){//成功
Log.e("YF", "onResponse: "+"YES" );//一个log,可以不写
message.what=1; //设置成功的指令为1
message.obj=response.body().bytes();//带入图片的数据
handler.sendMessage(message);//将指令和数据传出去
}else{//失败
Log.e("YF", "onResponse: "+"NO" );//一个log,可以不写
handler.sendEmptyMessage(0);//设置其他指令为零,然后进入handler
}
}
});
}
private void saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(),
"desheng");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(file.getPath()))));
}
private void initView() {
imageView = (ImageView) findViewById(R.id.imageView);
mybutton = (Button) findViewById(R.id.mybutton);
}
}
记得加网络权限,图片是加载的百度首页图片!!!