android文件保存与读取的几种方法_androidreader.exe.config.deploy-程序员宅基地

技术标签: android  存储  Android  

A:使用自建立应用包下/data/data/包名下的文件保存,不需要权限

1、页面布局截图

这里写图片描述

2、页面源代码

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:padding="10dp" >

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="2"
            android:gravity="center"
            android:text="账户:" />

        <EditText
            android:id="@+id/account"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="5"
            android:hint="请输入账号" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="2"
            android:gravity="center"
            android:text="密码:" />

        <EditText
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="5"
            android:hint="请输入密码"
            android:inputType="textPassword" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp" >

        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="是否记住密码" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingTop="5dp" >

        <Button
            android:id="@+id/exit"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:height="40dp"
            android:onClick="click"
            android:text="退出" />

        <Button
            android:id="@+id/login"
            android:layout_width="0dp"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:height="40dp"
            android:onClick="click"
            android:text="登录" />
    </TableRow>

</TableLayout>

3、文件保存与读取逻辑实现代码

public class MainActivity extends Activity {
    

    private CheckBox cb;
    private EditText et_account;
    private EditText et_password;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_table_login);

        cb = (CheckBox) findViewById(R.id.cb);
        et_account = (EditText) findViewById(R.id.account);
        et_password = (EditText) findViewById(R.id.password);

        file = new File(getFilesDir(), "config.txt");
        // 读取文件信息
        if (file.exists() && file.length() > 0) {

            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));

                String line = reader.readLine();

                String account = line.split("#!qishuichixi!#")[0];
                String password = line.split("#!qishuichixi!#")[1];

                et_account.setText(account);
                et_password.setText(password);

                // 组件获得焦点
                et_password.setFocusable(true);
                et_password.setFocusableInTouchMode(true);
                et_password.requestFocus();
                et_password.requestFocusFromTouch();

                cb.setChecked(true);

            } catch (Exception e) {

                Toast.makeText(this, "读取文件错误...", Toast.LENGTH_LONG).show();

            }

        }

    }

    public void click(View view) {

        String account = et_account.getText().toString().trim();
        String password = et_password.getText().toString().trim();

        switch (view.getId()) {
        case R.id.login:

            if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {

                // 提示语句
                Toast.makeText(this, "账号或则密码不能为空...", Toast.LENGTH_LONG).show();
                // 重置空白文本
                et_account.setText("");
                et_password.setText("");
                // 组件获得焦点
                et_account.setFocusable(true);
                et_account.setFocusableInTouchMode(true);
                et_account.requestFocus();
                et_account.requestFocusFromTouch();
                return;
            }

            if (cb.isChecked()) {

                // 第一种 保存文件信息 使用app自带文件夹
                // getCacheDir() 缓存文件夹
                // 不需要使用权限,即可保存下来
                String text = account + "#!qishuichixi!#" + password;

                try {
                    FileOutputStream outputStream = new FileOutputStream(file);

                    outputStream.write(text.getBytes("utf-8"));

                    outputStream.close();

                    Toast.makeText(this, "保存账号信息成功了...", Toast.LENGTH_LONG)
                            .show();

                } catch (Exception e) {

                    Toast.makeText(this, "保存账号信息出错了...", Toast.LENGTH_LONG)
                            .show();

                }

            }

            Toast.makeText(this, "登录成功...", Toast.LENGTH_LONG).show();

            break;
        case R.id.exit:

            finish();

            break;

        default:
            break;
        }

    }
}

4、文件保存路径
这里写图片描述

B:使用SD卡存储

1、新建SDActivity

public class SDActivity extends Activity {
    

    private CheckBox cb;
    private EditText et_account;
    private EditText et_password;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_table_login);

        cb = (CheckBox) findViewById(R.id.cb);
        et_account = (EditText) findViewById(R.id.account);
        et_password = (EditText) findViewById(R.id.password);

        // sd卡没处于挂载状态
        if (!Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {

            Toast.makeText(this, "sd卡错误...", Toast.LENGTH_LONG).show();

            return;
        }
        // sd卡剩余空间大小 字节
        long space = Environment.getExternalStorageDirectory().getFreeSpace();
        // 转换大小3.98GB
        String size = Formatter.formatFileSize(this, space);

        System.out.println("sd卡可用空间:" + size);
        // 存储路径   三种方式
        String path = Environment.getExternalStorageDirectory().getPath();
        // String path2="/sdcard/config.txt";
        // String path3=Environment.getExternalStorageDirectory().getPath()+"/config.txt";

        file = new File(path, "config.txt");
        // 读取文件信息
        if (file.exists() && file.length() > 0) {

            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));

                String line = reader.readLine();

                String account = line.split("#!qishuichixi!#")[0];
                String password = line.split("#!qishuichixi!#")[1];

                et_account.setText(account);
                et_password.setText(password);

                // 组件获得焦点
                et_password.setFocusable(true);
                et_password.setFocusableInTouchMode(true);
                et_password.requestFocus();
                et_password.requestFocusFromTouch();

                cb.setChecked(true);

            } catch (Exception e) {

                Toast.makeText(this, "读取文件错误...", Toast.LENGTH_LONG).show();

            }

        }

    }

    public void click(View view) {

        String account = et_account.getText().toString().trim();
        String password = et_password.getText().toString().trim();

        switch (view.getId()) {
        case R.id.login:

            if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {

                // 提示语句
                Toast.makeText(this, "账号或则密码不能为空...", Toast.LENGTH_LONG).show();
                // 重置空白文本
                et_account.setText("");
                et_password.setText("");
                // 组件获得焦点
                et_account.setFocusable(true);
                et_account.setFocusableInTouchMode(true);
                et_account.requestFocus();
                et_account.requestFocusFromTouch();
                return;
            }

            if (cb.isChecked()) {

                // 第一种 保存文件信息 使用app自带文件夹
                // getCacheDir() 缓存文件夹
                // 不需要使用权限,即可保存下来
                String text = account + "#!qishuichixi!#" + password;

                try {
                    FileOutputStream outputStream = new FileOutputStream(file);

                    outputStream.write(text.getBytes("utf-8"));

                    outputStream.close();

                    Toast.makeText(this, "保存账号信息成功了...", Toast.LENGTH_LONG)
                            .show();

                } catch (Exception e) {

                    Toast.makeText(this, "保存账号信息出错了...", Toast.LENGTH_LONG)
                            .show();

                }

            }

            Toast.makeText(this, "登录成功...", Toast.LENGTH_LONG).show();

            break;
        case R.id.exit:

            finish();

            break;

        default:
            break;
        }

    }
}

2、需要注意添加SD相关权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <!-- 允许挂载和反挂载文件系统可移动存储 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

3、设置SDActivity为启动activity

  <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

4、存储路径

这里写图片描述

C:使用shareprefer存储

1、建立SPActivity

public class SPActivity extends Activity {
    

    private CheckBox cb;
    private EditText et_account;
    private EditText et_password;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_table_login);

        cb = (CheckBox) findViewById(R.id.cb);
        et_account = (EditText) findViewById(R.id.account);
        et_password = (EditText) findViewById(R.id.password);

        // 读取文件信息

        sp = getSharedPreferences("config", Context.MODE_PRIVATE);

        String account = sp.getString("account", "");
        String password = sp.getString("password", "");

        et_account.setText(account);
        et_password.setText(password);

        if (account != "" && password != "") {
            // 组件获得焦点
            et_password.setFocusable(true);
            et_password.setFocusableInTouchMode(true);
            et_password.requestFocus();
            et_password.requestFocusFromTouch();

            cb.setChecked(true);
        }

    }

    public void click(View view) {

        String account = et_account.getText().toString().trim();
        String password = et_password.getText().toString().trim();

        switch (view.getId()) {
        case R.id.login:

            if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {

                // 提示语句
                Toast.makeText(this, "账号或则密码不能为空...", Toast.LENGTH_LONG).show();
                // 重置空白文本
                et_account.setText("");
                et_password.setText("");
                // 组件获得焦点
                et_account.setFocusable(true);
                et_account.setFocusableInTouchMode(true);
                et_account.requestFocus();
                et_account.requestFocusFromTouch();
                return;
            }

            if (cb.isChecked()) {

                try {

                    // 使用SharedPreferences保存xml数据 Context.MODE_PRIVATE等于0
                    SharedPreferences sp = getSharedPreferences("config",
                            Context.MODE_PRIVATE);
                    sp.edit().putString("account", account)
                            .putString("password", password).commit();

                    Toast.makeText(this, "保存账号信息成功了...", Toast.LENGTH_LONG)
                            .show();

                } catch (Exception e) {

                    Toast.makeText(this, "保存账号信息出错了...", Toast.LENGTH_LONG)
                            .show();

                }

            }

            Toast.makeText(this, "登录成功...", Toast.LENGTH_LONG).show();

            break;
        case R.id.exit:

            finish();

            break;

        default:
            break;
        }

    }

}

2、SharedPreferences保存xml文件截图

这里写图片描述

这里写图片描述

D:使用sqlite存储
E:源代码下载链接
http://download.csdn.net/detail/qq_30266985/9685053

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_30266985/article/details/53186229

智能推荐

Android磨砂图片处理(FastBlur)-程序员宅基地

文章浏览阅读4.4k次。Android磨砂图片处理(FastBlur)_fastblur

Python基础之time模块_python timeer-程序员宅基地

文章浏览阅读1.4k次。Python基础之time模块1.引入time模块import time2.获取时间戳(1)time.time()获取当前时间戳time1 = time.time()# 1532352941.8780842(2)time.localtime([sec]) 将时间戳格式化为本地时间,sec为指定时间戳,默认为当前时间time1 = time.loca..._python timeer

linux环境下使用netstat命令查看网络信息_linux netstat -ano-程序员宅基地

文章浏览阅读3.6k次,点赞2次,收藏13次。`netstat` 这个命令一直以为是 net status 的缩写,今天一查发现并没有找到官方的这种说法,然后参考了 man 手册,发现这个词更像是 net statistics 的缩写,命令的作用是显示网络连接、路由表、接口连接、无效连接和多播成员关系的..._linux netstat -ano

Sqlmap使用详解_--tamper=space2comment-程序员宅基地

文章浏览阅读3.1k次,点赞2次,收藏26次。目录SqlmapSqlmap的简单用法探测指定URL是否存在SQL注入漏洞查看数据库的所有用户(--users)查看数据库所有用户名的密码(--passwords)查看数据库当前用户(--current-user)判断当前用户是否有管理权限(--is-dba列出数据库管理员角色(--roles)查看所有的数据库(--dbs)查看当前的数据库(--current-db)爆出指定数据库中的所有的表爆..._--tamper=space2comment

burst什么意思_burst是什么意思_burst的用法-程序员宅基地

文章浏览阅读4.3k次。burst的音标英 [bɜːst]美 [bɜːrst]burst的用法v. (使)爆裂,胀开;猛冲;突然出现;爆满;涨满n. 突发;猝发;迸发;爆破;爆裂;裂口;一阵短促的射击第三人称单数: bursts 现在分词: bursting 过去式: burst 过去分词: burstburst的例句1.The driver lost control when a tyre burst一个车胎爆了,司机..._burst

第四章 IP地址和子网划分_判断属于哪个、子网-程序员宅基地

文章浏览阅读1.1k次。4.1 理解IP地址MAC地址和IP地址数据包的目标IP地址决定了数据包最终到达哪一个计算机,而目标MAC地址决定了该数据包下一跳由哪一个设备接收,不一定是终点MAC地址决定下一跳给哪个设备IP地址决定数据包最终给哪个计算机IP地址的组成计算机的IP地址由两部分组成,一部分为网络标识,一部分为主机标识,同一网段的计算机网络部分相同,路由器连接不同网段,负责不同网段之间的数据转发,交换..._判断属于哪个、子网

随便推点

zTree实现删除某个父节点后删除其下所有节点_ztree删除选中父节点-程序员宅基地

文章浏览阅读2.7k次。function onRemove(e, treeId, treeNode) { var newTree=$.fn.zTree.getZTreeObj("tree"); var act=newTree.transformToArray(treeNode.children); var allId=[]; allId.push(treeN_ztree删除选中父节点

jar包详解_jar包结构详解-程序员宅基地

文章浏览阅读8.2k次。1.可运行jar包和普通jar包及目录结构可运行jar包是打jar包时,指定了main-class类,可以通过java -jar xxx.jar 命令,执行main-class的main方法,运行jar包。可运行jar包不可被其他项目进行依赖。普通jar包打包时,不用指定main-class,也不可运行。普通jar包可以供其它项目进行依赖。jar包的配置文件是META-INF文件夹下的MANIFEST.MF文件。里面配置了如下信息:Manifest-Version用来定义manifest文件的版本_jar包结构详解

SpringAOP日志注解_spring aop 日志实现注解-程序员宅基地

文章浏览阅读819次。Spring AOP自定义注解_spring aop 日志实现注解

JAVA字符串转日期或日期转字符串_java200807转日期格式-程序员宅基地

文章浏览阅读2.5w次,点赞3次,收藏22次。用法: SimpleDateFormat sdf = new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " ); 这一行最重要,它确立了转换的格式,yyyy是完整的公元年,MM是月份,dd是日期,至于HH:mm:ss 就不需要我再解释了吧! PS:为什么有的格式大写,有的格式小写,那是怕避免混淆,例如MM是月..._java200807转日期格式

2024计算机考研《操作系统考研通关800题》下载分享_操作系统考研真题网盘-程序员宅基地

文章浏览阅读83次。B、中程调度的主要功能是当内存紧张是挂起部分暂时不运行的进程,并在内存有空闲时激活部分被挂起的进程,以提高内存利用与和系统吞吐量。[P1638] 在对记录型信号量的wait操作的定义中,当信号量的值( )时,执行wait操作的进程变为阻塞状态。[P1648] 作业的操作分为若干作业步,一个典型作业操作通常分为三个作业步,下列错误的是( )[P1637] 已知记录型信号量S,当前S.value的值为-5,下列选项错误的是( )A.用户数越少 B.用户数越多 C.内存越小 D.内存越大。_操作系统考研真题网盘

HadoopWindows权限异常_hadoop 正尝试在 windows 操作系统上使用 posix 文件权限相关的 api,导致该异-程序员宅基地

文章浏览阅读335次。1:报错如下java.io.IOException: (null) entry in command string: null chmod 0644复制代码解决方案1.下载winutils的windows版本在hadoop2.7.x版本里,请使用:https://github.com/SweetInk/hadoop-common-2.7.1-bin随便解压到一个目录,将加压出来的bin..._hadoop 正尝试在 windows 操作系统上使用 posix 文件权限相关的 api,导致该异常的