Android(java)学习笔记182:保存数据到SD卡 (附加:保存数据到内存)
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();
String MEDIA_BAD_REMOVAL
解释:返回getExternalStorageState() ,表明SDCard 被卸载前己被移除
解释:返回getExternalStorageState() ,表明对象正在磁盘检查。
解释:返回getExternalStorageState() ,表明存储媒体已经挂载,对象是否存在并具有读/写权限。
String MEDIA_MOUNTED_READ_ONLY
解释:返回getExternalStorageState() ,表明对象权限为只读。
解释:返回getExternalStorageState() ,表明对象为空白或正在使用不受支持的文件系统。
解释:返回getExternalStorageState() ,表明存储媒体被移除。
解释:返回getExternalStorageState() ,如果 SDCard 未安装 ,存储媒体正在通过USB共享
解释:返回getExternalStorageState() ,存储媒体无法挂载
解释:返回getExternalStorageState() ,存储媒体没有挂载
方法:getDataDirectory()
解释:返回 File ,获取 Android 数据目录。
解释:返回 File ,获取 Android 下载/缓存内容目录。
解释:返回 File ,获取外部存储目录即 SDCard
方法:getExternalStoragePublicDirectory(String type)
解释:返回 File ,取一个高端的公用的外部存储器目录来摆放某些类型的文件
解释:返回 File ,获取外部存储设备的当前状态
解释:返回 File ,获取 Android 的根目录

<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>
布局效果图,如下:

(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)学习笔记182:保存数据到SD卡 (附加:保存数据到内存)的更多相关文章
- java学习笔记06--正则表达式
java学习笔记06--正则表达式 正则表达式可以方便的对数据进行匹配,可以执行更加复杂的字符串验证.拆分.替换等操作. 例如:现在要去判断一个字符串是否由数字组成,则可以有以下的两种做法 不使用正则 ...
- Android(java)学习笔记125:保存数据到SD卡 (附加:保存数据到内存)
1. 如果我们要想读写数据到SD卡中,首先必须知道SD的路径: File file = new File(Environment.getExternalStorageDirectory()," ...
- Java学习笔记:基本输入、输出数据操作实例分析
Java学习笔记:基本输入.输出数据操作.分享给大家供大家参考,具体如下: 相关内容: 输出数据: print println printf 输入数据: Scanner 输出数据: JAVA中在屏幕中 ...
- Android 数字签名学习笔记
Android 数字签名学习笔记 在Android系统中,所有安装到系统的应用程序都必有一个数字证书,此数字证书用于标识应用程序的作者和在应用程序之间建立信任关系,如果一个permission的pro ...
- 0028 Java学习笔记-面向对象-Lambda表达式
匿名内部类与Lambda表达式示例 下面代码来源于:0027 Java学习笔记-面向对象-(非静态.静态.局部.匿名)内部类 package testpack; public class Test1{ ...
- 《Java学习笔记(第8版)》学习指导
<Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...
- Java学习笔记4
Java学习笔记4 1. JDK.JRE和JVM分别是什么,区别是什么? 答: ①.JDK 是整个Java的核心,包括了Java运行环境.Java工具和Java基础类库. ②.JRE(Java Run ...
- java学习笔记01--数据类型
java学习笔记01--数据类型 java数据类型划分 分为两大类型: 1)基本数据类型:类似于普通的值. 2)引用数据类型:传递的是内存的地址. 浮点类型实际上就是表示小数. java基本数据类型 ...
- java学习笔记13--比较器(Comparable、Comparator)
java学习笔记13--比较器(Comparable.Comparator) 分类: JAVA 2013-05-20 23:20 3296人阅读 评论(0) 收藏 举报 Comparable接口的作用 ...
随机推荐
- windows远程桌面连接配置
我的电脑 -> 属性 -> 远程 把两个checkbox勾上 运行(win + r) -> 输入secpol.msc回车 -> 找到本地策略 -> 安全选项 ->账 ...
- 李洪强iOS开发Swift篇—08_函数(2)
李洪强iOS开发Swift篇—08_函数(2) 一.函数类型 函数类型也是数据类型的一种,它由形参类型和返回值类型组成,格式是 (形参类型列表) -> 返回值类型 1 func sum(num1 ...
- [topcoder]ActivateGame
http://community.topcoder.com/stat?c=problem_statement&pm=10750&rd=14153 http://apps.topcode ...
- Android UI:机智的远程动态更新策略
问题描述 做过Android开发的人都遇到过这样的问题:随着需求的变化,某些入口界面通常会出现 UI的增加.减少.内容变化.以及跳转界面发生变化等问题.每次发生变化都要手动修改代码,而入口界面通常具有 ...
- WebService开发应用
WebService是运行于服务端(一般放在信息服务器上的)让客户端来调用的. 以下开发两个简单的实例 1.自己开发服务端自己调用(vs2010) 1).菜单:“新建-项目”,在打开的窗体中选择,如下 ...
- 【Python Network】使用DOM生成XML
单纯的为DOM树添加结点. #!/usr/bin/env python # Generating XML with DOM - Chapter 8 - domgensample.py from xml ...
- Drainage Ditches(Dinic最大流)
http://poj.org/problem?id=1273 用Dinic求最大流的模板题,注意会有重边. 邻接矩阵建图 #include<stdio.h> #include<str ...
- Unreachable catch block for IOException. This exception is never thrown from the try statement body
Unreachable catch block for IOException. This exception is never thrown from the try statement body ...
- android基本的数据库创建和使用
android的四大组件中就有Content Provider,对其他应用,提供自己的数据,所以,一般情况下,android应用不需要提供content provider. 1. 简单的数据库表单字 ...
- 在Code First中使用Migrations对实体类和数据库做出变更
在Code First中使用Migrations对实体类和数据库做出变更,Mirgration包含一系列命令. 工具--库程序包管理器--程序包管理器控制台 运行命令:Enable-Migration ...