Android笔记(四十八) Android中的资源访问——SDCard
访问存储在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的更多相关文章
- Android笔记(六十五) android中的动画——属性动画(propertyanimation)
补间动画只能定义起始和结束两个帧在“透明度”.“旋转”.“倾斜”.“位移”4个方面的变化,逐帧动画也只能是播放多个图片,无法满足我们日常复杂的动画需求,所以谷歌在3.0开始,推出了属性动画(prope ...
- Android笔记(七十五) Android中的图片压缩
这几天在做图记的时候遇第一次遇到了OOM,好激动~~ 追究原因,是因为在ListView中加载的图片太大造成的,因为我使用的都是手机相机直接拍摄的照片,图片都比较大,所以在加载的时候会出现内存溢出,那 ...
- Android笔记(六十八) Fragment总结
Fragment的产生: 为了适应各种尺寸的屏幕,谷歌推出Fragment,可以把Fragment成Activity的一个组成部分,它拥有自己的生命周期.可以接收并处理用户的各种事件,还可以动态的增删 ...
- Android笔记(六十六) android中的动画——XML文件定义属性动画
除了直接在java代码中定义动画之外,还可以使用xml文件定义动画,以便重用. 如果想要使用XML来编写动画,首先要在res目录下面新建一个animator文件夹,所有属性动画的XML文件都应该存放在 ...
- Android笔记(十八) 下拉列表(Spinner)
App中常用的控件——下拉列表(Spinner),提供特定选择供用户选择 Spinner每次只能选择一个部件,它的选项来自于与之相关联的适配器(apater)中. MainActivity.java ...
- Android笔记(十) Android中的布局——表格布局
TableLayout运行我们使用表格的方式来排列控件,它的本质依然是线性布局.表格布局采用行.列的形式来管理控件,TableLayout并不需要明确的声明包含多少行多少列,而是通过添加TableRo ...
- Java学习笔记二十八:Java中的接口
Java中的接口 一:Java的接口: 接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明.一个类通过继承接口的方式,从而来继承 ...
- 论文阅读笔记四十八: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 摘要 大规模的目标检测数据集在 ...
- Android为TV端助力 转载:Android绘图Canvas十八般武器之Shader详解及实战篇(上)
前言 Android中绘图离不开的就是Canvas了,Canvas是一个庞大的知识体系,有Java层的,也有jni层深入到Framework.Canvas有许多的知识内容,构建了一个武器库一般,所谓十 ...
随机推荐
- Android dump命令查看某个apk是被谁安装的?
adb shell dumpsys package packages > packageAll.txt ORadb shell pm dump packages > package ...
- 【翻译】Flink Table Api & SQL —— 数据类型
本文翻译自官网:https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/table/types.html Flink Table ...
- jwplayer :若请求不到流,则页面一直转圈请求效果
思路: 利用jwplayer onPlay(播放) .onError(出错)事件. 页面:背景图为黑色,嵌入一张背景为黑色的 git 动态图,加载页面时隐藏. 流程:若进入到onPlay 方法,则说明 ...
- [LeetCode] 337. House Robber III 打家劫舍 III
The thief has found himself a new place for his thievery again. There is only one entrance to this a ...
- [LeetCode] 752. Open the Lock 开锁
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', ...
- 【Python学习之十一】Numpy
环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 python3.6 1.介绍NumPy(Numerical Pyt ...
- 第07组 Beta冲刺(3/4)
队名:秃头小队 组长博客 作业博客 组长徐俊杰 过去两天完成的任务:学习了很多东西 Github签入记录 接下来的计划:继续学习 还剩下哪些任务:后端部分 燃尽图 遇到的困难:自己太菜了 收获和疑问: ...
- maven环境搭建教程
1.下载和解压 访问 maven.apache.org .点击download 下载对应系统的文件,window下载bin的zip文件. maven需要java1.7jdk支持,如果jdk没有 ...
- PHP阿里大于发短信教程
PHP阿里大于发短信教程 1 先去控制台 https://www.alidayu.com/center/user/account?spm=a3142.7791109.1999204004.5.ZtBQ ...
- Vue利用搜狐获取公网ip地址
在index.html中添加代码: <script src="https://pv.sohu.com/cityjson?ie=utf-8"></script> ...