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 / (去除文件的 ...
随机推荐
- 带jsk证书,请求https接口
首先是三个返回的实体类 BaseVo.java package https2; import java.io.Serializable; import java.lang.reflect.Invoca ...
- 【论文翻译】MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications 论文链接:https://arxi ...
- <2014 04 15> C++语言回顾精要(原创By Andrew)
C++语言回顾精要 <Visual C++程序设计>张岳新,这本书是很多学校的本科生C++教学用书,今天重新拿来翻了一遍.跟很多国人写的技术书籍一样,写书并不是为了让初学者看懂入门,而是为 ...
- centos7 docker镜像加速器配置
CentOS的配置方式略微复杂,需要先将默认的配置文件复制出来 /lib/systemd/system/docker.service -> /etc/systemd/system/docker. ...
- scrapy item
item item定义了爬取的数据的model item的使用类似于dict 定义 在items.py中,继承scrapy.Item类,字段类型scrapy.Field() 实例化:(假设定义了一个名 ...
- 5.MongoDB CRUD Operations-官方文档摘录
总结 1. CRUD:create, read, update, and delete DOCUMENT 2.在3.2版本的插入方式 db.collection.insertOne() db.coll ...
- python小知识点复习
join 与 split 对应,join传入的列表只包含字符串卡类型 字典 dic = {'x':1, 'y':2, 'x':3} print(dic) # {'x': 3, 'y': 2} 重复的k ...
- Leetcode 之 Exclusive Time of Functions
636. Exclusive Time of Functions 1.Problem Given the running logs of n functions that are executed i ...
- sql server中index的REBUILD和REORGANIZE的区别及工作方式
sql server中index的REBUILD和REORGANIZE 转自:https://www.cnblogs.com/flysun0311/archive/2013/12/05/3459451 ...
- EXP直接导出压缩问津,IMP直接导入压缩文件的方法
在10G之前,甚至在10G的Oracle环境中,有很多数据量不大,重要性不太高的系统依然采用EXP/IMP逻辑导出备份方式,或者,作为辅助备份方式. 通常情况下,我们都是这样操作的:1.exp导出2. ...