9.Android-读写SD卡案例
1.效果如下所示:

2.读写SD卡时,需要给APP添加读写外部存储设备权限,修改AndroidManifest.xml,添加:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如下图所示:

3.读写SD卡需要用到的Environment类
Environment类是一个提供访问环境变量的类.
Environment类常用的方法有:
static File getRootDirectory(); //获取根目录,默认位于:/system
static File getDataDirectory(); //获取data目录,默认位于:/data
static File getDownloadCacheDirectory(); //获取下载文件的缓存目录,默认位于:/cache static String getExternalStorageState();
//获取sd卡外部的状态,返回的内容可以判断sd卡是否被挂载.比如:
//判断if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))、除了MEDIA_MOUNTED("mounted")外,
//还可以通过MEDIA_MOUNTED_READ_ONLY("mounted_ro")来判断是否是只读挂载。 static File getExternalStoragePublicDirectory(String type); //获取sd卡指定的type标准目录
//type可以填入:
//DIRECTORY_ALARMS 系统提醒铃声存放的标准目录。
//DIRECTORY_DCIM 相机拍摄照片和视频的标准目录。
//DIRECTORY_DOWNLOADS 下载的标准目录。
//DIRECTORY_MOVIES 电影存放的标准目录。
//DIRECTORY_MUSIC 音乐存放的标准目录。
//DIRECTORY_NOTIFICATIONS 系统通知铃声存放的标准目录。
//DIRECTORY_PICTURES 图片存放的标准目录
//DIRECTORY_PODCASTS 系统广播存放的标准目录。
//DIRECTORY_RINGTONES 系统铃声存放的标准目录。 static File getExternalStorageDirectory(); //获取sd卡的路径
示例如下:
Log.d("MainActivity", Environment.getExternalStorageState());
Log.d("MainActivity", "getRootDirectory: "+Environment.getRootDirectory().getAbsolutePath().toString());
Log.d("MainActivity", "getDataDirectory: "+Environment.getDataDirectory().getAbsolutePath().toString());
Log.d("MainActivity", "getDownloadCacheDirectory: "+Environment.getDownloadCacheDirectory().getAbsolutePath().toString());
Log.d("MainActivity", "getExternalStorageDirectory: "+Environment.getExternalStorageDirectory().getAbsolutePath().toString());
Log.d("MainActivity", "DIRECTORY_ALARMS: "+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS).getAbsolutePath().toString());
Log.d("MainActivity", "DIRECTORY_DCIM: "+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath().toString());
Log.d("MainActivity", "DIRECTORY_DOWNLOADS: "+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath().toString());
打印:

4.写activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <TextView
android:id="@+id/text_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SD卡读写内容:" /> <EditText
android:id="@+id/et_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text_label"
android:minLines="5" /> <Button
android:id="@+id/btn_read"
android:layout_below="@id/et_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取内容" /> <Button
android:id="@+id/btn_write"
android:layout_below="@id/et_content"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="写入内容"
/> <TextView
android:id="@+id/text_sdSize"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="SD卡剩余:1KB 总:100KB" /> </RelativeLayout>
5.写Utils类(用于读写SD卡下的info.txt)
package com.example.utils;
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 android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.text.format.Formatter;
import android.util.Log; public class Utils {
//获取SD卡下的info.txt内容
static public String getSDCardInfo(){ if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
return null; File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/info.txt"); //打开要读的文件 if(!file.exists()) //文件不存在的情况下
{
Log.v("sdcard", "file is Empty");
return "";
}
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line = null; while((line=br.readLine())!=null) //获取每一行数据源
{
sb.append(line+"\r\n");
} return sb.toString(); } catch (IOException e) { e.printStackTrace(); return null;
}
} //将content写入SD卡下的info.txt
static public boolean writeSDCardInfo(String content){ if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
return false; File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/info.txt"); try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.flush();
fos.close();
return true; } catch (IOException e) { e.printStackTrace();
return false;
}
}
}
6.写MainActivity类
package com.example.sdreadWrite;
import java.io.File;
import com.example.utils.Utils;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.text.format.Formatter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity { private TextView text_sdSize;
private EditText et_content; protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); et_content = (EditText)findViewById(R.id.et_content);
text_sdSize = (TextView)findViewById(R.id.text_sdSize); //获取SD卡容量
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ text_sdSize.setText("未挂载SD卡,获取SD卡容量失败"); }else{ File externalStorageDirectory = Environment.getExternalStorageDirectory(); long totalSpace = externalStorageDirectory.getTotalSpace();
long freeSpace = externalStorageDirectory.getFreeSpace(); String totalSize = Formatter.formatFileSize(MainActivity.this, totalSpace); String freeSize = Formatter.formatFileSize(MainActivity.this, freeSpace); text_sdSize.setText("SD卡剩余:"+ freeSize+" 总:"+totalSize);
} Button btn_read = (Button)findViewById(R.id.btn_read);
//读取SD卡事件
btn_read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) { String content = Utils.getSDCardInfo(); if(content==null){ Toast.makeText(MainActivity.this,"读取失败",Toast.LENGTH_SHORT).show(); }else{
et_content.setText(content);
Toast.makeText(MainActivity.this,"读取成功",Toast.LENGTH_SHORT).show();
}
}
}); Button btn_write = (Button)findViewById(R.id.btn_write);
//写入sd卡事件
btn_write.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) { if(Utils.writeSDCardInfo(et_content.getText().toString())){ Toast.makeText(MainActivity.this,"写入成功",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this,"写入失败",Toast.LENGTH_SHORT).show();
}
}
});
} @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;
}
}
9.Android-读写SD卡案例的更多相关文章
- Android 读写SD卡的文件
今天介绍一下Android 读写SD卡的文件,要读写SD卡上的文件,首先需要判断是否存在SD卡,方法: Environment.getExternalStorageState().equals(Env ...
- android 读写sd卡的权限设置
原文:android 读写sd卡的权限设置 在Android中,要模拟SD卡,要首先使用adb的mksdcard命令来建立SD卡的镜像,如何建立,大家上网查一下吧,应该很容易找到,这里不说这个问题. ...
- Android读写SD卡
SD卡的读写是我们在开发Android 应用程序过程中最常见的操作.下面介绍SD卡的读写操作方式: 1. 获取SD卡的根目录 String sdCardRoot = Environment.getEx ...
- android读写SD卡封装的类
参考了网上的一些资源代码,FileUtils.java: package com.example.test; import java.io.BufferedInputStream; import ja ...
- android 读写SD卡文件
参考: http://www.oschina.net/code/snippet_176897_7336#11699 写文件: private void SavedToText(Context cont ...
- android学习笔记47——读写SD卡上的文件
读写SD卡上的文件 通过Context的openFileInput.openFileOutput来打开文件输入流.输出流时,程序打开的都是应用程序的数据文件夹里的文件,其存储的文件大小可能都比较有限- ...
- Android 常见SD卡操作
目录 Android 常见SD卡操作 Android 常见SD卡操作 参考 https://blog.csdn.net/mad1989/article/details/37568667. [0.] E ...
- android 向SD卡写入数据
原文:android 向SD卡写入数据 1.代码: /** * 向sdcard中写入文件 * @param filename 文件名 * @param content 文件内容 */ public v ...
- Android 检测SD卡应用
Android 检测SD卡应用 // Environment.MEDIA_MOUNTED // sd卡在手机上正常使用状态 // ...
随机推荐
- upstream--负载
语法格式: upstream 负载名 { [ip_hash;] server ip:port [weight=数字] [down]; server ip:port [weight=数字]; } ...
- pytest封神之路第二步 132个命令行参数用法
在Shell执行pytest -h可以看到pytest的命令行参数有这10大类,共132个 序号 类别 中文名 包含命令行参数数量 1 positional arguments 形参 1 2 gene ...
- 关于input框仿百度/google自动提示的方法
引入jquery-autocomplete文件 链接:https://pan.baidu.com/s/1hW0XBYH8ZgJgMSY1Ce6Pig 密码:tv5b $(function() { $( ...
- python基础一(安装、变量、循环、git)
一.开发语言分类 系统的开发语言有java.c++.c#.python.ruby.php等等,开发语言可分为编译型语言和解释型语言. 编译型语言就是写好代码之后就把代码编译成二进制文件,运行的时候运行 ...
- 【漫话DevOps】What is DevOps?
最近几年"DevOps"这个关键词经常出现在项目开发当中,特别是随着微服务/容器/cloud在项目中的大范围应用,你不想知道都很难.作为一个伴随CI/CD到DevOps一路走来的工 ...
- redis设置密码和查询密码
编辑redis.windows.conf配置来启用认证. 1.初始化Redis密码: 在配置文件中有个参数: requirepass 这个就是配置redis访问密码的参数: 比如 requirepa ...
- v-charts 绘制柱状图、条形图、水球图、雷达图、折线图+柱状图,附官网地址
v-charts 官网地址:https://v-charts.js.org/#/ 柱状图: <template> <ve-histogram :data="chartDat ...
- hystrix源码之插件
HystrixPlugins 获取并发相关类(HystrixConcurrencyStrategy).事件通知类(HystrixEventNotifier).度量信息类(HystrixMetricsP ...
- luogu2756 飞行员配对方案问题 (裸匈牙利)
匈牙利: 4 81 51 62 53 53 74 54 74 8-1 -1 out:4 #include<iostream> #include<cstdio> #include ...
- MySQL中的临时表到底什么是?
Author:极客小俊 一个专注于web技术的80后 我不用拼过聪明人,我只需要拼过那些懒人 我就一定会超越大部分人! CSDN@极客小俊,原创文章, B站技术分享 B站视频 : Bilibili.c ...