访问存储在SD卡中的文件

使用 Environment.getExternalStorageState(); 判断是否存在内存卡

使用 Environment.getExternalStorageDirectory() 来获取内存卡的根目录路径

内存卡写入:

MainActivity.java

package cn.lixyz.iotest.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import cn.lixyz.iotest.R;
import cn.lixyz.iotest.util.IOFile; public class MainActivity extends Activity implements OnClickListener { private Button bt_sdcard_exist, bt_sdcard_write;
private EditText et_sdcard_input; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); findView();
bt_sdcard_exist.setOnClickListener(this);
bt_sdcard_write.setOnClickListener(this);
} public void findView() {
bt_sdcard_exist = (Button) findViewById(R.id.bt_sdcard_exist);
bt_sdcard_write = (Button) findViewById(R.id.bt_sdcard_write);
et_sdcard_input = (EditText) findViewById(R.id.et_sdcard_input);
} @Override
public void onClick(View v) {
IOFile ioFile;
switch (v.getId()) {
case R.id.bt_sdcard_exist:
ioFile = new IOFile(this);
ioFile.sdCardExist();
break;
case R.id.bt_sdcard_write:
String inputString = et_sdcard_input.getText().toString();
ioFile = new IOFile(this);
ioFile.writeToSDCard(inputString);
break; default:
break;
}
} }

activity_main.xml

<LinearLayout 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:orientation="vertical"
tools:context="cn.lixyz.iotest.activity.MainActivity" > <Button
android:id="@+id/bt_sdcard_exist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="判断手机是否安装内存卡" /> <EditText
android:id="@+id/et_sdcard_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入您要写入的内容" /> <Button
android:id="@+id/bt_sdcard_write"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SDCard写入" /> </LinearLayout>

IOFile.java

package cn.lixyz.iotest.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException; import android.content.Context;
import android.os.Environment;
import android.widget.Toast; public class IOFile { Context mContext; // 在构造函数中创建一个Context参数,用于在非Activity处弹出Toast
public IOFile(Context context) {
mContext = context;
} public void sdCardExist() {
// 判断手机收安装内存卡,如果没有安装,则弹出提示
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(mContext, "您没有安装SD卡", Toast.LENGTH_SHORT).show();
}
} public void writeToSDCard(String str) { try {
// 获取内存卡跟路径
String sdCardDir = Environment.getExternalStorageDirectory().toString();
File fileName = new File(sdCardDir + "/" + "fileForSDCard.txt");
if (!fileName.exists()) {
fileName.createNewFile();
} //写入文件
FileWriter fileWriter = new FileWriter(fileName);
fileWriter.write(str);
       fileWriter.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

这样运行,会提示权限错误:

需要给工程添加权限:

    <!-- 在内存卡中创建文件和删除文件的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 向内存卡写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

运行结果:

内存卡读取:

MainActivity.java

package cn.lixyz.iotest.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import cn.lixyz.iotest.R;
import cn.lixyz.iotest.util.IOFile; public class MainActivity extends Activity implements OnClickListener { private Button bt_sdcard_exist, bt_sdcard_write, bt_sdcard_read;
private EditText et_sdcard_input; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); findView();
bt_sdcard_exist.setOnClickListener(this);
bt_sdcard_write.setOnClickListener(this);
bt_sdcard_read.setOnClickListener(this);
} public void findView() {
bt_sdcard_exist = (Button) findViewById(R.id.bt_sdcard_exist);
bt_sdcard_write = (Button) findViewById(R.id.bt_sdcard_write);
et_sdcard_input = (EditText) findViewById(R.id.et_sdcard_input);
bt_sdcard_read = (Button) findViewById(R.id.bt_sdcard_read);
} @Override
public void onClick(View v) {
IOFile ioFile;
switch (v.getId()) {
case R.id.bt_sdcard_exist:
ioFile = new IOFile(this);
ioFile.sdCardExist();
break;
case R.id.bt_sdcard_write:
ioFile = new IOFile(this);
String inputString = et_sdcard_input.getText().toString();
ioFile.writeToSDCard(inputString);
break;
case R.id.bt_sdcard_read:
ioFile = new IOFile(this);
ioFile.readFromSDCard();
break;
}
} }

activity_main.xml

<LinearLayout 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:orientation="vertical"
tools:context="cn.lixyz.iotest.activity.MainActivity" > <Button
android:id="@+id/bt_sdcard_exist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="判断手机是否安装内存卡" /> <EditText
android:id="@+id/et_sdcard_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入您要写入的内容" /> <Button
android:id="@+id/bt_sdcard_write"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SDCard写入" /> <Button
android:id="@+id/bt_sdcard_read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SDCard读取" /> </LinearLayout>

IOFile.java

package cn.lixyz.iotest.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.Flushable;
import java.io.IOException;
import java.io.UnsupportedEncodingException; import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast; public class IOFile { Context mContext; // 在构造函数中创建一个Context参数,用于在非Activity处弹出Toast
public IOFile(Context context) {
mContext = context;
} // 判断手机是否安装内存卡
public void sdCardExist() {
// 判断手机收安装内存卡,如果没有安装,则弹出提示
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(mContext, "您没有安装SD卡", Toast.LENGTH_SHORT).show();
}
} // 往内存卡中写入内容
public void writeToSDCard(String str) {
try {
// 获取内存卡跟路径
String sdCardDir = Environment.getExternalStorageDirectory().toString();
File fileName = new File(sdCardDir + "/" + "fileForSDCard.txt");
if (!fileName.exists()) {
fileName.createNewFile();
}
// 写入文件
FileWriter fileWriter = new FileWriter(fileName);
fileWriter.write(str);
fileWriter.flush(); } catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // 从内存卡中读取内容
public void readFromSDCard() {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + "fileForSDCard.txt");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
fileInputStream.close(); String str = new String(bytes);
Log.d("TTT", "文件内容是:" + str); } catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.lixyz.iotest"
android:versionCode="1"
android:versionName="1.0" > <!-- 在内存卡中创建文件和删除文件的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 向内存卡写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="cn.lixyz.iotest.activity.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>

运行结果:

  

Android笔记(四十八) Android中的资源访问——SDCard的更多相关文章

  1. Android笔记(六十五) android中的动画——属性动画(propertyanimation)

    补间动画只能定义起始和结束两个帧在“透明度”.“旋转”.“倾斜”.“位移”4个方面的变化,逐帧动画也只能是播放多个图片,无法满足我们日常复杂的动画需求,所以谷歌在3.0开始,推出了属性动画(prope ...

  2. Android笔记(七十五) Android中的图片压缩

    这几天在做图记的时候遇第一次遇到了OOM,好激动~~ 追究原因,是因为在ListView中加载的图片太大造成的,因为我使用的都是手机相机直接拍摄的照片,图片都比较大,所以在加载的时候会出现内存溢出,那 ...

  3. Android笔记(六十八) Fragment总结

    Fragment的产生: 为了适应各种尺寸的屏幕,谷歌推出Fragment,可以把Fragment成Activity的一个组成部分,它拥有自己的生命周期.可以接收并处理用户的各种事件,还可以动态的增删 ...

  4. Android笔记(六十六) android中的动画——XML文件定义属性动画

    除了直接在java代码中定义动画之外,还可以使用xml文件定义动画,以便重用. 如果想要使用XML来编写动画,首先要在res目录下面新建一个animator文件夹,所有属性动画的XML文件都应该存放在 ...

  5. Android笔记(十八) 下拉列表(Spinner)

    App中常用的控件——下拉列表(Spinner),提供特定选择供用户选择 Spinner每次只能选择一个部件,它的选项来自于与之相关联的适配器(apater)中. MainActivity.java ...

  6. Android笔记(十) Android中的布局——表格布局

    TableLayout运行我们使用表格的方式来排列控件,它的本质依然是线性布局.表格布局采用行.列的形式来管理控件,TableLayout并不需要明确的声明包含多少行多少列,而是通过添加TableRo ...

  7. Java学习笔记二十八:Java中的接口

    Java中的接口 一:Java的接口: 接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明.一个类通过继承接口的方式,从而来继承 ...

  8. 论文阅读笔记四十八:Bounding Box Regression with Uncertainty for Accurate Object Detection(CVPR2019)

    论文原址:https://arxiv.org/pdf/1809.08545.pdf github:https://github.com/yihui-he/KL-Loss 摘要 大规模的目标检测数据集在 ...

  9. Android为TV端助力 转载:Android绘图Canvas十八般武器之Shader详解及实战篇(上)

    前言 Android中绘图离不开的就是Canvas了,Canvas是一个庞大的知识体系,有Java层的,也有jni层深入到Framework.Canvas有许多的知识内容,构建了一个武器库一般,所谓十 ...

随机推荐

  1. NPOI导出EXCEL样式

    public void Export(DataRequest<ExportModel> request, DataResponse<dynamic> response) { t ...

  2. EasyNVR摄像机网页H5全平台无插件直播流媒体播放服务二次开发之接口鉴权示例讲解

    背景需求 EasyNVR的使用者应该都清楚的了解到,EasyNVR一个强大的功能就是可以进行全平台的无插件直播.主要原因在于rtsp协议的视频流(默认是需要插件才可以播放的)经由EasyNVR处理可以 ...

  3. [简短问答]LODOP打印不清晰

    用什么语句输出的:使用的的是什么语句输出的,是ADD_PRINT_TEXT纯文本,还是html的超文本. 超文本不清晰:如果用的是ADD_PRINT_HTML ,换成 ADD_PRINT_HTM试试, ...

  4. [LeetCode] 89. Gray Code 格雷码

    The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...

  5. 【SSH进阶之路】Spring的AOP逐层深入——AOP的基本原理(六)

    经过我们对Spring的IOC不断的深入学习,Spring的面貌逐渐变得清晰,我们对Spring的了解也更加的深入.从这篇博文开始我们学习Spring的第二大核心内容:AOP. 什么是AOP AOP( ...

  6. idea2018.1.1版激活码到2020.7

    N757JE0KCT-eyJsaWNlbnNlSWQiOiJONzU3SkUwS0NUIiwibGljZW5zZWVOYW1lIjoid3UgYW5qdW4iLCJhc3NpZ25lZU5hbWUiO ...

  7. LeetCode 22. 括号生成(Generate Parentheses)

    22. 括号生成 22. Generate Parentheses 题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n = 3,生成结 ...

  8. [转帖]Introduction to Linux monitoring and alerting

    Introduction to Linux monitoring and alerting https://www.redhat.com/sysadmin/linux-monitoring-and-a ...

  9. 《算法 - Lru算法》

    一:概述 - LRU 用于管理缓存策略,其本身在 Linux/Redis/Mysql 中均有实现.只是实现方式不尽相同. - LRU 算法[Least recently used(最近最少使用)] - ...

  10. 链表习题(6)-链表返回倒数第k个数的位置的值

    /*链表返回倒数第k个数的位置的值*/ /* 算法思想:先取得链表的长度len,之后获取len-k+1的位置元素的值 */ Elemtype Getelem_rear(LinkList L, int ...