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卡在手机上正常使用状态 // ...
随机推荐
- OneDrive 折腾记
起因 百度云的一系列劝退操作 OneDrive 5T 有点香 OneDrive 介绍 OneDrive有两种, 个人版 OneDrive 和 教育企业版 OneDrive for Business 个 ...
- leetcode刷题-64最小路径和
题目 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小. 说明:每次只能向下或者向右移动一步. 示例: 输入:[ [1,3,1], [1,5, ...
- SSM框架中添加写日志功能
前提:要导入log4j的jar包 在web.xml中输入: <!--日志加载--> <context-param> <param-name>log4jConfigL ...
- window下dos命令
引用 Windows下DOS命令 显示当前目录所有文件 dir 创建文件夹 md test 创建文件 cd>a.txt 删除文件 del a.txt 删除文件夹 rd test 在某磁盘打开不同 ...
- Linux下vim的安装及配置
目录 一.vim的下载 二.vim的基本知识 三.vim的基本配置 四.vim与外部文件的复制粘贴 一.vim的下载 Ubuntu系统,输入命令: sudo apt install vim Cento ...
- 将微服务部署到 Azure Kubernetes 服务 (AKS) 实践
本文是对 <.NET Tutorial - Deploy a microservice to Azure> 的翻译和实践.入门级踩坑实践,k8s 大佬请回避,以免耽误您宝贵的时间. 介绍 ...
- Java 的各种内部类、Lambda表达式
内部类 内部类是指在一个外部类的内部再定义一个类.内部类的出现,再次打破了Java单继承的局限性. 内部类可以是静态 static 的,也可用 public,default,protected 和 p ...
- Java链接db2相关
端口一般是50000或者60000 后面跟的可能是库名(个人猜测) 还有db2jcc.jar安装db2的可以从相应目录下载未安装的可以…(啥时候有空再传上来)
- 2. 构建DNS集群
DNS是什么 DNS(Domain Name System,域名系统),是互联网上存储域名和IP映射关系的一个分布式数据库,他负责把域名转换为IP地址,或IP转换为域名,工作于OSI应用层之上,DNS ...
- 分布式系统监视zabbix讲解六之自定义监控项
概述 Zabbix支持许多在多种情况下使用宏.宏是一个变量,由如下特殊语法标识: {MACRO} 根据在上下文中, 宏解析为一个特殊的值. 有效地使用宏可以节省时间,并使Zabbix变地更加高效. 在 ...