获取文件保存路径及数据回显

一、获取保存的文件的路径

 //如何获取到文件保存的路径
            File fileDir =this.getFilesDir();
            Log.d(TAG,"files dir =="+fileDir.toString());

 对代码进行改进,并利用adb命令删除之前的info.txt文件

private void saveUserInfo(String usernameText,String passwordText){
            Log.d(TAG,"保存用户信息");
            //如何获取到文件保存的路径
            File fileDir =this.getFilesDir();
            File saveFile= new File(fileDir,"info.txt");
            //此代码在控制台打印文件保存的路径
            Log.d(TAG,"files dir =="+fileDir.toString());
            try  {
            if(saveFile.exists()){
                saveFile.createNewFile();
            }
                FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
                //以特定的格式存储
                fileOutputStream.write((usernameText+"***"+passwordText).getBytes());
                fileOutputStream.close();
            }catch (Exception e){
                  e.printStackTrace();
            }
        }

运行代码

 查看info.txt

 与输入内容一致

再次修改代码,输出缓存文件目录

//获取到缓存文件储存的路径
            File cacheDir = this.getCacheDir();
            Log.d(TAG,"cache  Dir =="+cacheDir);

/**
             * files dir ==/data/user/0/com.example.logindemo/files
             * 上面这个路径是用来保存文件的,我们可以通过代码命令行删除,也可以通过设置里的应用设置列表进行设置
             * cache  Dir ==/data/user/0/com.example.logindemo/cache
             * 上面这个路径是用来保存缓存文件的,这个目录下的文件,系统会根据内存进行自动处理。
             */

 这里的清除缓存即可删除保存的文件

二、对输入内容进行判空

//对账号和密码进行检测
            if(TextUtils.isEmpty(usernameText)){
                //账号为空
                Toast.makeText(this,"用户名不可以为空",Toast.LENGTH_SHORT).show();
                return;
            }
            if(TextUtils.isEmpty(passwordText)){
                //密码为空
                Toast.makeText(this,"密码不可以为空",Toast.LENGTH_SHORT).show();
            }

 

 三、读取数据回显

@Override
     protected void onResume(){
         super.onResume();
            try  {
                FileInputStream fileInputStream =this.openFileInput("info.txt");
                BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(fileInputStream));
                String info=bufferedReader.readLine();
                //以特定的格式存储
                //fileOutputStream.write((usernameText+"***"+passwordText).getBytes());
                //上面是数据存储的格式
                String [] splits=info.split("\\*\\*\\*");
                String username =splits[0];
                String password =splits[1];
                //回显数据
                mUsername.setText(username);
                mPassword.setText(password);
            }catch (Exception e){
                e.printStackTrace();
            }
     }

原文地址:https://www.cnblogs.com/yeyueweiliang/p/12250488.html