当前位置: 首页 > news >正文

001 Android TextUtils工具类的使用

1.采用File类,在指定目录下读写数据

java后台代码为:

(1)向app的/data/data/com.example.lucky.helloworld目录下写入文本(涉及IO的读写操作)

package com.example.lucky.helloworld;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class UserInfoUtils {
    public static boolean saveInfo(String username,String password){
        String result=username+"=="+password;
        //创建File类,指定数据存储位置
        File file=new File("/data/data/com.example.lucky.helloworld/info.txt");
        try {
            //创建一个文件的输出流
            FileOutputStream fos=new FileOutputStream(file);
            fos.write(result.getBytes()); //向文件中写入数据
            fos.close();  //关闭文件
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //读取用户信息
    public static Map<String,String> readInfo(){
        //定义map
        Map<String,String> map=new HashMap<>();
        File file=new File("/data/data/com.example.lucky.helloworld/info.txt");
        try {
            FileInputStream fis=new FileInputStream(file);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            String strTemp=br.readLine();  //读取数据
            String[] splitstr=strTemp.split("=="); //对字符串进行切割
            String username=splitstr[0];
            String password=splitstr[1];
            map.put("name",username);  //将数据放入map集合中
            map.put("pw",password);
            fis.close(); //关闭数据流
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

 

(2)MainActivity.java代码

package com.example.lucky.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Map;

public class MainActivity extends AppCompatActivity {
    EditText et_username;
    EditText et_password;
    Button bt_login;

    //当Activityq启动时就会执行onCreate方法
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置activity的内容,内容来自布局文件activity_main.xml
        setContentView(R.layout.activity_main);
        Log.v("001","我是verbose级别");
        Log.i("001","我是info级别");
        Log.d("001","我是debug级别");
        Log.w("001","我是warn级别");
        Log.e("001","我是error级别");
        System.out.println("sout输出");
        et_username=findViewById(R.id.et_username);
        et_password=findViewById(R.id.et_password);
        bt_login=findViewById(R.id.bt_login);

        //读取/data/data/com.example.lucky.helloworld/info.txt文件
        Map<String,String> map=UserInfoUtils.readInfo();
        if(map!=null){
            String name=map.get("name");
            String password=map.get("pw");
            et_username.setText(name);  //将读取的数据显示出来
        }


        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username=et_username.getText().toString();
                String password=et_password.getText().toString();
                //安卓特有的工具类,用来判断string是否为空
                if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)){
                    Toast.makeText(MainActivity.this,"用户名不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    boolean result=UserInfoUtils.saveInfo(username,password);
                    if(result){
                        Toast.makeText(MainActivity.this,"数据存储成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this,"数据存储失败",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
}

 2.利用Context类获取常用目录,存储文件(推荐使用)

文件数据保存的模式:

1)MODE_PRIVATE ,这个模式用得最多,其他的模式很少用

2)MODE_APPEND

3)MODE_WORLD_READABLE

4)MODE_WORLD_WRITEABLE

(1)读写工具类

package com.example.lucky.helloworld;

import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class UserInfoUtils {
    public static boolean saveInfo(Context context, String username, String password){
        String result=username+"=="+password;

        try {
            //创建一个文件的输出流,使用上下文获取常用目录
            FileOutputStream fos=context.openFileOutput("info2.txt",Context.MODE_PRIVATE);
            fos.write(result.getBytes()); //向文件中写入数据
            fos.close();  //关闭文件
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //读取用户信息
    public static Map<String,String> readInfo(Context context){
        //定义map
        Map<String,String> map=new HashMap<>();
        try {
            FileInputStream fis=context.openFileInput("info2.txt");
            BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            String strTemp=br.readLine();  //读取数据
            String[] splitstr=strTemp.split("=="); //对字符串进行切割
            String username=splitstr[0];
            String password=splitstr[1];
            map.put("name",username);  //将数据放入map集合中
            map.put("pw",password);
            fis.close(); //关闭数据流
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

(2)MainActivity.class

package com.example.lucky.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    EditText et_username;
    EditText et_password;
    Button bt_login;
    Button bt_private;
    Button bt_append;
    Button bt_readable;
    Button bt_writeable;

    //当Activityq启动时就会执行onCreate方法
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置activity的内容,内容来自布局文件activity_main.xml
        setContentView(R.layout.activity_main);
        init();

        //info2.txt文件
        Map<String,String> map=UserInfoUtils.readInfo(MainActivity.this);
        if(map!=null){
            String name=map.get("name");
            String password=map.get("pw");
            et_username.setText(name);  //将读取的数据显示出来
        }

        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username=et_username.getText().toString();
                String password=et_password.getText().toString();
                //安卓特有的工具类,用来判断string是否为空
                if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)){
                    Toast.makeText(MainActivity.this,"用户名不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    boolean result=UserInfoUtils.saveInfo(MainActivity.this,username,password);
                    if(result){
                        Toast.makeText(MainActivity.this,"数据存储成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this,"数据存储失败",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        //在data/data/com.example.lucky.helloworld下创建files文件夹,生成属性为private的文件
        bt_private.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileOutputStream fos=openFileOutput("private.txt",MODE_PRIVATE); //创建private.txt
                    fos.write("private".getBytes());  //写入数据
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        //在data/data/com.example.lucky.helloworld下创建files文件夹,生成属性为append(可追加内容)的文件
        bt_append.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileOutputStream fos=openFileOutput("append.txt",MODE_APPEND);
                    fos.write("append".getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        //在data/data/com.example.lucky.helloworld下创建files文件夹,生成属性为MODE_WORLD_READABLE的文件,只读模式
        bt_readable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileOutputStream fos=openFileOutput("readable.txt",MODE_WORLD_READABLE);
                    fos.write("readable".getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        bt_writeable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileOutputStream fos=openFileOutput("writeable.txt",MODE_WORLD_WRITEABLE);
                    fos.write("writeable".getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void init() {
        et_username=findViewById(R.id.et_username);
        et_password=findViewById(R.id.et_password);
        bt_login=findViewById(R.id.bt_login);
        bt_private=findViewById(R.id.bt_private);
        bt_append=findViewById(R.id.bt_append);
        bt_readable=findViewById(R.id.bt_readable);
        bt_writeable=findViewById(R.id.bt_writeable);
    }
}

 

转载于:https://www.cnblogs.com/luckyplj/p/10610810.html

相关文章:

  • windows下安装oracle11g测试是否成功与监听器问题和网页控制台登录
  • unity复制到剪切板
  • 软件开发的权限控制和权限验证
  • PBR论文链接
  • 词频统计
  • 云时代架构阅读笔记四——深入的、详细的介绍Map以及HashMap
  • The Blinn-Phong Normalization Zoo
  • PAT甲级——1134 Vertex Cover (25 分)
  • 控制特效在UI上面
  • python-opencv学习第一章
  • Hive启动失败
  • kajiya-kay 头发
  • Prncnfg.vbs参数详解
  • Docker安装
  • Precomputed Radiance Transfer for Real-Time Rendering in Dynamic, Low-Frequency Lighting Environment
  • 【399天】跃迁之路——程序员高效学习方法论探索系列(实验阶段156-2018.03.11)...
  • 【RocksDB】TransactionDB源码分析
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • Magento 1.x 中文订单打印乱码
  • node入门
  • Python十分钟制作属于你自己的个性logo
  • 从零开始学习部署
  • 基于Mobx的多页面小程序的全局共享状态管理实践
  • 记一次删除Git记录中的大文件的过程
  • 技术:超级实用的电脑小技巧
  • 面试总结JavaScript篇
  • 学习使用ExpressJS 4.0中的新Router
  • ​批处理文件中的errorlevel用法
  • # include “ “ 和 # include < >两者的区别
  • # Pytorch 中可以直接调用的Loss Functions总结:
  • #Java第九次作业--输入输出流和文件操作
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • $.ajax,axios,fetch三种ajax请求的区别
  • (LNMP) How To Install Linux, nginx, MySQL, PHP
  • (第61天)多租户架构(CDB/PDB)
  • (二)换源+apt-get基础配置+搜狗拼音
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (已解决)vue+element-ui实现个人中心,仿照原神
  • (转)清华学霸演讲稿:永远不要说你已经尽力了
  • .NET Conf 2023 回顾 – 庆祝社区、创新和 .NET 8 的发布
  • .Net Core与存储过程(一)
  • .NET 表达式计算:Expression Evaluator
  • .NET8.0 AOT 经验分享 FreeSql/FreeRedis/FreeScheduler 均已通过测试
  • .NET关于 跳过SSL中遇到的问题
  • .NET中winform传递参数至Url并获得返回值或文件
  • /bin、/sbin、/usr/bin、/usr/sbin
  • @DateTimeFormat 和 @JsonFormat 注解详解
  • @Import注解详解
  • @Mapper作用
  • [ 2222 ]http://e.eqxiu.com/s/wJMf15Ku
  • [ 渗透工具篇 ] 一篇文章让你掌握神奇的shuize -- 信息收集自动化工具
  • [20180224]expdp query 写法问题.txt
  • [AutoSar]BSW_Memory_Stack_004 创建一个简单NV block并调试
  • [Docker]三.Docker 部署nginx,以及映射端口,挂载数据卷
  • [HEOI2013]ALO