Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)

时间:2022-11-05 04:26:12

1. 如果我们要想读写数据到SD卡中,首先必须知道SD的路径:

File file = new File(Environment.getExternalStorageDirectory(),"info.txt");
FileOutputStream fos = new FileOutputStream(file);//打开输出流,相应的路径下创建文件info.txt

fos.write("This is a good Boy".getBytes());  //public void write(byte[] buffer) throws IOException {……};

                                                                      //public byte[] getBytes() {……}
fos.close();

2. Environment 是一个提供访问环境变量的类。Environment 包含常量:
String MEDIA_BAD_REMOVAL
解释:返回getExternalStorageState() ,表明SDCard 被卸载前己被移除
String MEDIA_CHECKING
解释:返回getExternalStorageState() ,表明对象正在磁盘检查。
String MEDIA_MOUNTED
解释:返回getExternalStorageState() ,表明存储媒体已经挂载,对象是否存在并具有读/写权限。

String MEDIA_MOUNTED_READ_ONLY

解释:返回getExternalStorageState() ,表明对象权限为只读。
String MEDIA_NOFS
解释:返回getExternalStorageState() ,表明对象为空白或正在使用不受支持的文件系统。
String MEDIA_REMOVED
解释:返回getExternalStorageState() ,表明存储媒体被移除。
String MEDIA_SHARED
解释:返回getExternalStorageState() ,如果 SDCard 未安装 ,存储媒体正在通过USB共享
String MEDIA_UNMOUNTABLE
解释:返回getExternalStorageState() ,存储媒体无法挂载
String MEDIA_UNMOUNTED
解释:返回getExternalStorageState() ,存储媒体没有挂载
 
Environment 常用方法:
方法:getDataDirectory()
解释:返回 File ,获取 Android 数据目录。
方法:getDownloadCacheDirectory()
解释:返回 File ,获取 Android 下载/缓存内容目录。
方法:getExternalStorageDirectory()
解释:返回 File ,获取外部存储目录即 SDCard

方法:getExternalStoragePublicDirectory(String type)

解释:返回 File ,取一个高端的公用的外部存储器目录来摆放某些类型的文件
方法:getExternalStorageState()
解释:返回 File ,获取外部存储设备的当前状态
方法:getRootDirectory()
解释:返回 File ,获取 Android 的根目录
 
3. 这里使用Environment.getExternalStorageDirectory()获得当前SD的目录,这是Google提供的获取外部存储SD卡目录的API,但是很多厂家往往自己设定SD卡的目录,
这样导致的结果就是:刚刚Environment.getExternalStorageDirectory()就不能有效找到SD卡的目录,所以通常有时候程序开发的时候,写入数据到SD卡的时候,开始会有几百行代码判断SD卡路径(穷举判断)
类似于:
   if() {
  ……
    }
  if() {
  ……
    }
  if() {
  ……
    }
 
3. 保存数据到手机内存之中:
(1)Context.getFilesDir():
保存文件到手机内存:data/data/包名/文件名
(2)Context.getCacheDir()
保存文件到手机内存:data/data/cache/文件名
 
4. 保存数据到SD 和 保存数据到内存之中的综合案例:
(1)新建一个 Android工程,如下:
Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)
 
 
(2)首先我们来到主布局文件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="com.himi.filetosd.MainActivity" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="QQ账号"
android:textSize="10sp"
/>
<EditText
android:id="@+id/et_qq"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
/>
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="QQ账号"
android:textSize="10sp"
/>
<EditText
android:id="@+id/et_password"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:inputType="textPassword"
/>
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkbox"
/>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
/>
</LinearLayout> </LinearLayout>

布局效果图,如下:

Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)

(3)这里要使用的SD卡存储数据,需要添加相应的权限,如下:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

(4)这里需要保存数据到手机内存 ,同时也需要保存数据到sd卡之中,这里我们特定写了一个工具类Tools:

 package com.himi.filetosd.utils;

 import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; import android.content.Context;
import android.os.Environment; public class ToolsFile { public static final String FILE_NAME = "info.txt";
/**
* 保存文件到手机内存:data/data/包名/info.txt
* @param context
* @param username
* @param password
* @return
*/
public static boolean saveFileToPackage(Context context, String username,
String password) {
File file = new File(context.getFilesDir(),FILE_NAME);
try {
FileWriter fw = new FileWriter(file);
fw.write(username+":"+password);
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
} /**
* 保存文件到手机内存:data/data/cache/info.txt
* @param context
* @param username
* @param password
* @return
*/
public static boolean saveFileToCache(Context context, String username,
String password) {
File file = new File(context.getCacheDir(),FILE_NAME);
try {
FileWriter fw = new FileWriter(file);
fw.write(username+":"+password);
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
} /**
* 删除data/data/包名/info.txt文件
* @param context
* @return
*/
public static boolean delete(Context context) {
File file = new File(context.getFilesDir(),FILE_NAME);
return file.delete();
} /**
* 保存文件到SD:/mnt/sdcard
*/
public static boolean saveFileToSD(Context context, String username,
String password) {
//判断sd有没有安装
if(!Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED)) {
return false;
} File file = new File(Environment.getExternalStorageDirectory(),FILE_NAME);
try {
FileWriter fw = new FileWriter(file);
fw.write(username+":"+password);
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} return true;
} /**
* 查询mnt/sdcard目录下info.txt文件信息,以字符串的形式反馈
* @param context
* @return
*/
public static String findUser(Context context) {
File file = new File(Environment.getExternalStorageDirectory(), FILE_NAME);
// 如果文件不存在则返回 null
if (!file.exists()) {
return null;
}
String result = null;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
result = reader.readLine();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
} }

(5)来到MainActivity,如下:

 package com.himi.filetosd;

 import com.himi.filetosd.utils.ToolsFile;

 import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity {
public static String qqCode = "10086";
public static String passwordCode = "123456"; private EditText et_qq;
private EditText et_password;
private CheckBox cb;
private Button login; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); initViews();
initEvents(); String user = ToolsFile.findUser(this);
if(user != null) {
String[] split = user.split(":");
et_qq.setText(split[0]);
et_password.setText(split[1]);
}
} private void initEvents() {
save.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
String qq = et_qq.getText().toString();
String password = et_password.getText().toString();
boolean checked = cb.isChecked(); /*
* 用户名和密码如果为空,则提示用户。
*/
if (TextUtils.isEmpty(qq)) {
Toast.makeText(MainActivity.this, "用户名不能为空!",
Toast.LENGTH_SHORT).show();
return ;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(MainActivity.this, "密码不能为空! ",
Toast.LENGTH_SHORT).show();
return ;
} if(qq.equals(qqCode) && password.equals(passwordCode)) {
if (checked) {
ToolsFile.saveFileToSD(MainActivity.this, qq, password);
} else {
ToolsFile.delete(MainActivity.this);
}
Toast.makeText(MainActivity.this, "登录成功 ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "登录失败 ",
Toast.LENGTH_SHORT).show();
} }
}); } private void initViews() {
// TODO Auto-generated method stub
et_qq = (EditText) findViewById(R.id.et_qq);
et_password = (EditText) findViewById(R.id.et_password);
cb = (CheckBox) findViewById(R.id.checkbox);
login= (Button) findViewById(R.id.login); } }

(6)布署程序到模拟器上,如下:

  • 刚刚启动程序如下:

Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)

  • 输入错误的账号信息

Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)

  • 输入正确的账号信息

Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)

Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)

Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)