• Android(java)学习笔记125:保存数据到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();

    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工程,如下:
     
     
    (2)首先我们来到主布局文件activity_main.xml,如下:
     1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     xmlns:tools="http://schemas.android.com/tools"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     android:orientation="vertical"
     6     tools:context="com.himi.filetosd.MainActivity" >
     7 
     8     <LinearLayout
     9         android:layout_width="match_parent"
    10         android:layout_height="wrap_content" 
    11         android:layout_marginTop="50dp" 
    12         android:orientation="horizontal" >
    13         <TextView 
    14             android:layout_width="0dp"
    15             android:layout_height="wrap_content"
    16             android:layout_weight="1"
    17             android:text="QQ账号"
    18             android:textSize="10sp"
    19             />
    20         <EditText 
    21             android:id="@+id/et_qq"
    22             android:layout_width="0dp"
    23             android:layout_height="wrap_content"
    24             android:layout_weight="4"
    25             />
    26      </LinearLayout>
    27      
    28     <LinearLayout
    29         android:layout_width="match_parent"
    30         android:layout_height="wrap_content" 
    31         android:layout_marginTop="20dp" 
    32         android:orientation="horizontal" >
    33         <TextView 
    34             android:layout_width="0dp"
    35             android:layout_height="wrap_content"
    36             android:layout_weight="1"
    37             android:text="QQ账号"
    38             android:textSize="10sp"
    39             />
    40         <EditText 
    41             android:id="@+id/et_password"
    42             android:layout_width="0dp"
    43             android:layout_height="wrap_content"
    44             android:layout_weight="4"
    45             android:inputType="textPassword"
    46             />
    47      </LinearLayout>
    48      
    49     <LinearLayout
    50         android:layout_width="match_parent"
    51         android:layout_height="wrap_content" 
    52         android:layout_marginTop="20dp" 
    53         android:gravity="center_horizontal"
    54         android:orientation="horizontal" >
    55         <CheckBox 
    56             android:layout_width="wrap_content"
    57             android:layout_height="wrap_content"
    58                android:id="@+id/checkbox"
    59             />
    60         <Button 
    61             android:id="@+id/login"
    62             android:layout_width="wrap_content"
    63             android:layout_height="wrap_content"
    64             android:text="登录"
    65             />
    66      </LinearLayout>
    67 
    68 </LinearLayout>

    布局效果图,如下:

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

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

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

      1 package com.himi.filetosd.utils;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.File;
      5 import java.io.FileReader;
      6 import java.io.FileWriter;
      7 import java.io.IOException;
      8 
      9 import android.content.Context;
     10 import android.os.Environment;
     11 
     12 public class ToolsFile {
     13     
     14     public static final String FILE_NAME = "info.txt";
     15     /**
     16      * 保存文件到手机内存:data/data/包名/info.txt
     17      * @param context
     18      * @param username
     19      * @param password
     20      * @return
     21      */
     22     public static boolean saveFileToPackage(Context context, String username,
     23             String password) {
     24         File file =  new File(context.getFilesDir(),FILE_NAME);
     25         try {
     26             FileWriter fw = new FileWriter(file);
     27             fw.write(username+":"+password);
     28             fw.close();
     29         } catch (IOException e) {
     30             // TODO Auto-generated catch block
     31             e.printStackTrace();
     32             return false;
     33         }
     34         return true;
     35     }
     36     
     37     /**
     38      * 保存文件到手机内存:data/data/cache/info.txt
     39      * @param context
     40      * @param username
     41      * @param password
     42      * @return
     43      */
     44     public static boolean saveFileToCache(Context context, String username,
     45             String password) {
     46         File file =  new File(context.getCacheDir(),FILE_NAME);
     47         try {
     48             FileWriter fw = new FileWriter(file);
     49             fw.write(username+":"+password);
     50             fw.close();
     51         } catch (IOException e) {
     52             // TODO Auto-generated catch block
     53             e.printStackTrace();
     54             return false;
     55         }
     56         return true;
     57     }
     58     
     59     /**
     60      * 删除data/data/包名/info.txt文件
     61      * @param context
     62      * @return
     63      */
     64     public static boolean delete(Context context) {
     65         File file = new File(context.getFilesDir(),FILE_NAME);
     66         return file.delete();
     67     }
     68     
     69     /**
     70      * 保存文件到SD:/mnt/sdcard
     71      */
     72     public static boolean saveFileToSD(Context context, String username,
     73             String password) {
     74         //判断sd有没有安装
     75         if(!Environment.getExternalStorageState()
     76                 .equals(Environment.MEDIA_MOUNTED)) {
     77             return false;
     78         }
     79         
     80         File file = new File(Environment.getExternalStorageDirectory(),FILE_NAME);
     81         try {
     82             FileWriter fw = new FileWriter(file);
     83             fw.write(username+":"+password);
     84             fw.close();
     85         } catch (IOException e) {
     86             // TODO Auto-generated catch block
     87             e.printStackTrace();
     88             return false;
     89         }
     90         
     91         return true;
     92     }
     93     
     94     /**
     95      * 查询mnt/sdcard目录下info.txt文件信息,以字符串的形式反馈
     96      * @param context
     97      * @return
     98      */
     99     public static String findUser(Context context) {
    100         File file = new File(Environment.getExternalStorageDirectory(), FILE_NAME);
    101         // 如果文件不存在则返回 null
    102         if (!file.exists()) {
    103             return null;
    104         }
    105         String result = null;
    106         try {
    107             BufferedReader reader = new BufferedReader(new FileReader(file));
    108             result = reader.readLine();
    109             reader.close();
    110         } catch (Exception e) {
    111             e.printStackTrace();
    112         }
    113         return result;
    114     }
    115 
    116 }

    (5)来到MainActivity,如下:

     1 package com.himi.filetosd;
     2 
     3 import com.himi.filetosd.utils.ToolsFile;
     4 
     5 import android.app.Activity;
     6 import android.os.Bundle;
     7 import android.text.TextUtils;
     8 import android.view.View;
     9 import android.view.View.OnClickListener;
    10 import android.widget.Button;
    11 import android.widget.CheckBox;
    12 import android.widget.EditText;
    13 import android.widget.Toast;
    14 
    15 public class MainActivity extends Activity {
    16     public static String qqCode = "10086";
    17     public static String passwordCode = "123456";
    18 
    19     private EditText et_qq;
    20     private EditText et_password;
    21     private CheckBox cb;
    22     private Button login;
    23 
    24     @Override
    25     protected void onCreate(Bundle savedInstanceState) {
    26         super.onCreate(savedInstanceState);
    27         setContentView(R.layout.activity_main);
    28 
    29         initViews();
    30         initEvents();
    31         
    32         String user = ToolsFile.findUser(this);
    33         if(user != null) {
    34             String[] split = user.split(":");
    35             et_qq.setText(split[0]);
    36             et_password.setText(split[1]);
    37         }
    38     }
    39 
    40     private void initEvents() {
    41         save.setOnClickListener(new OnClickListener() {
    42             
    43             @Override
    44             public void onClick(View v) {
    45                 String qq = et_qq.getText().toString();
    46                 String password = et_password.getText().toString();
    47                 boolean checked = cb.isChecked();
    48                 
    49                 /*
    50                 * 用户名和密码如果为空,则提示用户。
    51                 */
    52                 if (TextUtils.isEmpty(qq)) {
    53                     Toast.makeText(MainActivity.this, "用户名不能为空!",
    54                             Toast.LENGTH_SHORT).show();
    55                     return ;
    56                 }
    57                 if (TextUtils.isEmpty(password)) {
    58                     Toast.makeText(MainActivity.this, "密码不能为空! ",
    59                             Toast.LENGTH_SHORT).show();
    60                     return ;
    61                 }
    62                 
    63                 if(qq.equals(qqCode) && password.equals(passwordCode)) {
    64                     if (checked) {
    65                         ToolsFile.saveFileToSD(MainActivity.this, qq, password);    
    66                     } else {
    67                         ToolsFile.delete(MainActivity.this);
    68                     }
    69                     Toast.makeText(MainActivity.this, "登录成功 ",
    70                             Toast.LENGTH_SHORT).show();
    71                 } else {
    72                     Toast.makeText(MainActivity.this, "登录失败 ",
    73                             Toast.LENGTH_SHORT).show();
    74                 }
    75                 
    76                 
    77             }
    78         });
    79         
    80     }
    81 
    82     private void initViews() {
    83         // TODO Auto-generated method stub
    84         et_qq = (EditText) findViewById(R.id.et_qq);
    85         et_password = (EditText) findViewById(R.id.et_password);
    86         cb = (CheckBox) findViewById(R.id.checkbox);
    87         login= (Button) findViewById(R.id.login);
    88 
    89     }
    90 
    91 }

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

    • 刚刚启动程序如下:

    • 输入错误的账号信息

    • 输入正确的账号信息

  • 相关阅读:
    MySQL Unable to convert MySQL datetime value to System.DateTime 解决方案
    Zend 无限试用
    SQL 触发器
    C# 多线程示例
    JS 实现打印
    apache开启.htaccess
    MySQL 安装包下载教程
    js系列(10)js的运用(二)
    js系列(9)js的运用(一)
    js系列(8)简介
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4745236.html
Copyright © 2020-2023  润新知