Android -- 读写文件到内部ROM,SD卡,SharedPreferences,文件读写权限
(内容整理自张泽华教程)
1. 概述
使用文件进行数据存储
首先给大家介绍使用文件如何对数据进行存储,Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的。
public class FileActivity extends Activity {
@Override public void onCreate(Bundle savedInstanceState) {
...
FileOutputStream outStream = this.openFileOutput("itcast.txt", Context.MODE_PRIVATE);
outStream.write("传智播客".getBytes());
outStream.close();
}
}
openFileOutput()方法的第一参数用于指定文件名称,不能包含路径分隔符“/”
,如果文件不存在,Android
会自动创建它。创建的文件保存在/data/data/<package name>/files目录,如:
/data/data/cn.itcast.action/files/itcast.txt,通过点击Eclipse菜单“Window”-“Show View”-“Other”,在对话窗口中展开android文件夹,选择下面的File
Explorer视图,然后在File Explorer视图中展开/data/data/<package name>/files目录就可以看到该文件。
openFileOutput()方法的第二参数用于指定操作模式,有四种模式,分别为:
Context.MODE_PRIVATE =
0
Context.MODE_APPEND =
32768
Context.MODE_WORLD_READABLE = 1
Context.MODE_WORLD_WRITEABLE = 2
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
如果希望文件被其他应用读和写,可以传入:
openFileOutput("itcast.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
读取文件内容
如果要打开存放在/data/data/<package name>/files目录应用私有的文件,可以使用Activity提供openFileInput()方法。
FileInputStream inStream = this.getContext().openFileInput("itcast.txt");
Log.i("FileTest", readInStream(inStream));
readInStream()的方法请看本页下面备注。
或者直接使用文件的绝对路径:
File file = new File("/data/data/cn.itcast.action/files/itcast.txt");
FileInputStream inStream = new FileInputStream(file);
Log.i("FileTest", readInStream(inStream));
注意:上面文件路径中的“cn.itcast.action”为应用所在包,当你在编写代码时应替换为你自己应用使用的包。
对于私有文件只能被创建该文件的应用访问,如果希望文件能被其他应用读和写,可以在创建文件时,指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
Activity还提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data/<package name>/cache目录
getFilesDir()方法用于获取/data/data/<package name>/files目录
把文件存放在SDCard
在程序中访问SDCard,你需要申请访问SDCard的权限。
在AndroidManifest.xml中加入访问SDCard的权限如下:
<!-- 在SDCard中创建与删除文件权限
-->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限
-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
要往SDCard存放文件,程序必须先判断手机是否装有SDCard,并且可以进行读写。
注意:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File saveFile = new File(sdCardDir, “itcast.txt”);
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("传智播客".getBytes());
outStream.close();
}
Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,当然要获取SDCard的目录,你也可以这样写:
File sdCardDir = new File("/mnt/sdcard"); //获取SDCard目录
File saveFile = new File(sdCardDir, "itcast.txt");
//上面两句代码可以合成一句:
File saveFile = new File("/mnt/sdcard/itcast.txt");
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("传智播客test".getBytes());
outStream.close();
2. 示例代码
获取SD卡大小示例代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tv_sdsize);
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
long sizeAvailSize = blockSize * availableBlocks;
String str = Formatter.formatFileSize(this, sizeAvailSize);
tv.setText(str);
}
数据存储示例代码:
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=".MainActivity" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/input_name" /> <EditText
android:id="@+id/et_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text" /> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/input_password" /> <EditText
android:id="@+id/et_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" /> <RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" > <CheckBox
android:id="@+id/cb_remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/remember_pwd" /> <Button
android:onClick="login"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login" />
</RelativeLayout> <RadioGroup
android:id="@+id/rg_save_location"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" > <RadioButton
android:id="@+id/rb_rom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="ROM" /> <RadioButton
android:id="@+id/rb_sd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SD" /> <RadioButton
android:id="@+id/rb_sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SP" />
</RadioGroup> </LinearLayout>
AndroidManifest.xml SD权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.login"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima.login.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>
SaveService.java 业务类
package com.itheima.login.service; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map; import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment; import com.itheima.login.utils.StreamTools; public class SaveService {
/**
* 保存数据到手机rom的文件里面.
* @param context 应用程序的上下文 提供环境
* @param name 用户名
* @param password 密码
* @throws Exception
*/
public static void saveToRom(Context context, String name , String password) throws Exception{
//File file = new File("/data/data/com.itheima.login/files/pwd.txt");
File file = new File(context.getFilesDir(),"pwd.txt");
FileOutputStream fos = new FileOutputStream(file);
String txt = name+":"+password;
fos.write(txt.getBytes());
fos.flush();
fos.close();
}
/**
* 从rom读取用户的密码信息
* @param context
* @return
*/
public static String readFromRom(Context context) throws Exception{
File file = new File(context.getFilesDir(),"pwd.txt");
FileInputStream fis = new FileInputStream(file);
String result = StreamTools.readFromStream(fis);
return result;
} /**
* 保存数据到SD卡
* @param name 用户名
* @param password 密码
* @throws Exception
*/
public static void saveTOSD(String name ,String password) throws Exception{
File file = new File(Environment.getExternalStorageDirectory(),"pwd.txt");
FileOutputStream fos = new FileOutputStream(file);
String txt = name+":"+password;
fos.write(txt.getBytes());
fos.flush();
fos.close();
} /**
* 保存应用程序数据 到sharedpreference
* @param context 上下文
* @param name 姓名
* @param password 密码
*/
public static void saveTOSP (Context context, String name, String password){
//获取系统的一个sharedpreference文件 名字叫 sp
SharedPreferences sp = context.getSharedPreferences("sp", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
//创建一个编辑器 可以编辑 sp
Editor editor = sp.edit();
editor.putString("name", name);
editor.putString("password", password);
editor.putBoolean("boolean", false);
editor.putInt("int", 8888);
editor.putFloat("float",3.14159f);
//注意:调用 commit 提交 数据到文件.
editor.commit();
//editor.clear();
} /**
* 获取系统sharepreference里面的数据
* @param context
* @return
*/
public static Map<String,String> readFromSP(Context context){
Map<String,String> map = new HashMap<String, String>();
SharedPreferences sp = context.getSharedPreferences("sp", Context.MODE_PRIVATE);
String name = sp.getString("name", "defaultname");
String password = sp.getString("password", "password");
map.put("name", name);
map.put("password", password);
return map;
} }
MainActivity.java
package com.itheima.login; import java.util.Map; import com.itheima.login.service.SaveService; import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast; public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private EditText et_name;
private EditText et_password;
private CheckBox cb_remember;
private RadioGroup rg_save_location; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_password = (EditText) findViewById(R.id.et_password);
cb_remember = (CheckBox) findViewById(R.id.cb_remember);
rg_save_location = (RadioGroup) findViewById(R.id.rg_save_location); // 检查 rom文件里面是否 有 密码信息
/*try {
String result = SaveService.readFromRom(this);
String[] infos = result.split(":");
et_name.setText(infos[0]);
et_password.setText(infos[1]);
} catch (Exception e) {
e.printStackTrace();
}*/ //获取sp里面的数据 Map<String, String> map = SaveService.readFromSP(this);
et_name.setText(map.get("name"));
et_password.setText(map.get("password")); } public void login(View view) {
String name = et_name.getText().toString().trim();
String password = et_password.getText().toString().trim();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
Toast.makeText(this, R.string.error_msg, Toast.LENGTH_SHORT).show();
return;
}
if (cb_remember.isChecked()) {
Log.i(TAG, "记住密码");
Log.d(TAG, "NAME=" + name);
Log.d(TAG, "PASSWORD=" + password);
int radiobuttonId = rg_save_location.getCheckedRadioButtonId();
switch (radiobuttonId) {
case R.id.rb_rom:
try {
SaveService.saveToRom(this, name, password);
Toast.makeText(this, "保存rom用户名密码 成功", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "保存rom用户名密码 失败", Toast.LENGTH_LONG)
.show();
}
break; case R.id.rb_sd:
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
try {
SaveService.saveTOSD(name, password);
Toast.makeText(this, "保存sd用户名密码 成功", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "保存sd用户名密码 失败", Toast.LENGTH_LONG)
.show();
}
}else{
Toast.makeText(this, "sd卡不可用 ,请检查sd卡状态", 0).show();
}
break; case R.id.rb_sp:
SaveService.saveTOSP(this, name, password);
Toast.makeText(this, "保存到sp完成", 0).show();
break;
} } else {
Log.i(TAG, "不需要记住密码");
} } }
Android -- 读写文件到内部ROM,SD卡,SharedPreferences,文件读写权限的更多相关文章
- 单元测试+内存、SD卡、SP读写+XmlPullParser
测试: 测试的相关概念 1.根据是否知道源代码分类: 黑盒测试: a - b - c 边值测试 测试逻辑业务 白盒测试: 根据源代码写测试方法 或者 测试用例; 2.根据测试的粒度分类: 方法测试:写 ...
- Android 读写SD卡的文件
今天介绍一下Android 读写SD卡的文件,要读写SD卡上的文件,首先需要判断是否存在SD卡,方法: Environment.getExternalStorageState().equals(Env ...
- 快速解决设置Android 23.0以上版本对SD卡的读写权限无效的问题
快速解决设置Android 23.0以上版本对SD卡的读写权限无效的问题 转 https://www.jb51.net/article/144939.htm 今天小编就为大家分享一篇快速解决设置And ...
- 转-Android 之 使用File类在SD卡中读取数据文件
如果需要在程序中使用sdcard进行数据的存储,那么需要在AndroidMainfset.xml文件中 进行权限的配置: Java代码: <!-- 在sd中创建和删除文件的权限 --> ...
- Android SD卡创建文件和文件夹失败
原文:Android SD卡创建文件和文件夹失败 功能需要,尝试在本地sd卡上创建文件和文件夹的时候,报错,程序崩溃. 一般情况下,是忘记给予sd卡的读写权限.但是这里面权限已经给了,还是报错. 在网 ...
- Android开发之下载Tomcat服务器的文件到模拟器的SD卡
Tomcat服务器可以到Apache的官网去下载http://tomcat.apache.org/,如何配置和使用百度下也有很多介绍,只要把Java的SDK配下java_home环境变量就行了,因为T ...
- Android从raw、assets、SD卡中获取资源文件内容
先顺带提一下,raw文件夹中的文件会和project一起经过编译,而assets里面的文件不会~~~ 另外,SD卡获取文件需要权限哦! //从res文件夹中的raw 文件夹中获取文件并读取数据 p ...
- Android—将Bitmap图片保存到SD卡目录下或者指定目录
直接上代码就不废话啦 一:保存到SD卡下 File file = new File(Environment.getExternalStorageDirectory(), System.currentT ...
- Android--手持PDA读取SD卡中文件
近两年市场上很多Wince设备都开始转向Android操作系统,最近被迫使用Android开发PDA手持设备.主要功能是扫描登录,拣货,包装,发货几个功能.其中涉及到商品档的时候大概有700左右商品要 ...
- 模拟器下的虚拟sd卡添加文件
1.若出现mkdir failed for myData Read-only file system,在执行 adb shell 命令后,执行mount -o remount ,rw / (去除文件的 ...
随机推荐
- oracle 实现多字段匹配一个关键字查询语句
oracle 实现多字段匹配一个关键字查询语句:有两种方法(经测试,10g中不能用,11g才行): 第一种. select * from table where ('字段名1' ||'字段名2' || ...
- POJ 2773 Happy 2006(容斥原理+二分)
Happy 2006 Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 10827 Accepted: 3764 Descr ...
- 用jQuery的attr()设置option默认选中无效的解决 attr设置属性失效
表单下拉选项使用selected设置,发现第一次默认选中成功,在页面不刷新的情况下,再次下拉,selected属性设置了,默认选中不生效 在手机端有些浏览器用jQuery的attr()方法设置sele ...
- SQSERVER--函数、开窗函数,-特殊的内容 (for xml path )
1.STUFF SQL Server之深入理解STUFF sql stuff函数用于删除指定长度的字符,并可以在制定的起点处插入另一组字符.sql stuff函数中如果开始位置或长度值是负数,或者如果 ...
- HTTP缓存实现的原理
浏览器是如何知道使用缓存的,其实这都是通过http中,浏览器将最后修改时间发送请求给web服务器,web服务器收到请求后跟服务器上的文档最后修改的时间对比,如果web服务器上最新文档修改时间小于或者等 ...
- Qt 打印机支持模块
Qt 打印支持 Qt为打印提供广泛的跨平台支持.使用每个平台上的打印系统,Qt应用程序可以打印到连接的打印机,并通过网络打印到远程打印机.Qt的打印系统还支持PDF文件生成,为基本的报告生成设施奠定了 ...
- Swift学习笔记四:数组和字典
Swift 提供两种集合类型来存储集合,数组和字典. 数组是一个同类型的序列化列表集合.字典是一个能够使用相似于键的唯一标识符来获取值的非序列化集合.也就是说数组是有序的.字典是无序的. 一. 数 ...
- blogCMS中出现的错误整理
1.在写日期归档的时候,出现如下错误: not enough values to unpack (expected 2, got 1) 出现这个错误是因为:字符串需要能够split成2份才能赋值给2个 ...
- beego——参数配置
beego目前支持INI.XML.JSON.YAML格式的配置文件解析,但是默认采用了INI格式解析,用户可以通过简单的配置就可以获得很大的灵活性. 一.默认配置解析 beego 默认会解析当前应用下 ...
- maven项目打WAR包记录
打了个war包,各种不顺,也是以前没打过的原因,眼高手低了…… cmd 进入项目目录 打开 运行----cmd 进入命令窗口 键入 cd 回车 输入E\:mars\cdc 键入 mvn clean p ...