安卓开发之文件存储(一)

  安卓开发时,最常见的就是,最普遍的操作就是对用户的账户密码的保存,然而将信息进行保存的方式有多种,刚接触信息的保存,介绍下其中一种(文件存储),但是这种却不是很严谨,下面代码也不是特别好,还有待改进。

  文件存储是Android中最基本的一种数据存储方式,他不对存储的内容进行任何的格式化处理。所有数据都是原封不动地保存到文件当中的,因而他比较适合用于存储一些简单的文本数据或二进制数据。如果你想使用文件存储的方式来保存一些较为复杂的文件数据,就需要定义一套自己的格式规范,这样可以方便之后将数据从文件中重新解析出来

  Content类中提供了一个openFileOutput()方法,可以用于将数据存储到指定的文件中,包含两个参数,一个是文件名(不需要包含路径,因为所有的文件都是默认存储到/data/data/<packagename>/files/目录下的)。另一参数是文件的操作模式,主要有拉ing汇总模式可选,MODE_PRIVATE,MODE_APPEND.openFileOutput()方法返回的是一个FileOutputStream对象,得到了这个对象之后就可以使用java流的方式将数据写入到文件中了。以下是一段简单的代码,展示了如何将一段文本内容保存到文件中。

View Code

  这里通过openFileOutput()方法能够得到一个FielOutputStream对象,然后借助它构
建出一个OutputStreamWriter独享,接着再使用OutputStreamWriter构建出一个BufferedWriter对象,
这样你就可以通过BufferedWriter来将文本内容写入到文件中了。

  从文件中读取数据,这个方法要比openFielOutput()简单一些,它只接受一个参数,既要读取文件名,然后系统会自动到/data/data/<package name>/files/目录下去加载这个文件,宁返回一FileInputStream对象,得到这个对象之后再通过java流的方式就可以将数据读取出来了。

public String load(String fielName){
    FileInputStream =null;
    BUfferedReader = null;
    StringBuilder content = new StringBuilder();
    
    try{
           in = openFileInpit(fileName);
           reader  = new BufferedReader(new INputStreamReader(in));
           String line = "";
            while((line=reader.readLine())!=null){
             content.append(line)
}
}catch(IOException e){
          e.printStackTrace();
}finally{
      if(reader!=null){
           try{
                   reader.close();
}catch(IOException e){
       e.printStackTrace();
}

}

}return content.toString();
}    

  在这段代码中,首先通过openFileInput()方法获取到一个FileInputStream对象,然后借助它构建出了一个InputStreamReader对象,接着在使用InputStreamReader构建一个BufferedReader对象,这样我们就可以通过BufferedReader进行一行行地读取,把文件中所有的文本内容全部读取出来,并存放在一个STringBuilder对象中,最后将读取到的内容返回就可以了。

  因为正常的登录都是可以选择是否记住账户密码功能的,所以在activity被销毁的时候,我们加入:

@Override
public void onDestroy(){
    super.onDestroy();
    if(remeber.isChecked())   //rember为CheckBox
{
    String u=username.getText().toString();
    String p=password.getText().toString();
     save(u,userNameDataFile);
     save(p,passwordDataFile);
}
}    

  当选择checkbox时,会获取edittext中的String,然后保存到userNameDataFile和passwordDataFile中,

  使用TextUtils.isEmpty()判断字符串是否为空,当传入为空格时,字符串长度为0,返回false

  

public static boolean isEmpty(CharSqquence str){
if(str == null\\str.length() ==0)
return true;
else
return false;
}

MainActivity.class

public class MainActivity extends AppCompatActivity {
    String userNameDataFile="userNameData";
    String passwordDataFile="passwordDara";
    String fileName = "data";
    private Button logining;
    private EditText username;
    private EditText password;
    CheckBox remeber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logining = (Button) findViewById(R.id.login);
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        remeber  = (CheckBox)findViewById(R.id.remeber);
        String userNameData = load(userNameDataFile);    //回显
        String userPasswordData = load(passwordDataFile);   //回显
        if (!TextUtils.isEmpty(userNameData)&&!TextUtils.isEmpty(userPasswordData)) {
            username.setText(userNameData);
            password.setText(userPasswordData);
            Toast.makeText(MainActivity.this, "Restory     succeeded", Toast.LENGTH_SHORT).show();
        }

        logining.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String usernames=username.getText().toString();
            String passwords=password.getText().toString();
            if(usernames.equals("")|passwords.equals("")){
                Toast.makeText(MainActivity.this,"账号或者密码不能为空",Toast.LENGTH_SHORT).show();
            }else if(usernames.equals("machutao")&&passwords.equals("12345678")){
                    Toast.makeText(MainActivity.this,"登陆成功",Toast.LENGTH_SHORT).show();
                    Intent intent= new Intent(MainActivity.this,logined.class);
                    intent.putExtra("username",usernames.trim());
                    intent.putExtra("password",passwords.trim());
                    startActivity(intent);
                }else{
                    Toast.makeText(MainActivity.this,"用户名或者密码不正确",Toast.LENGTH_SHORT).show();
                }
            }


    });
    }
    @Override
    public  void onDestroy(){
        super.onDestroy();
        if(remeber.isChecked()){
            String u= username.getText().toString();
            String p= password.getText().toString();
            save(u,userNameDataFile);
            save(p,passwordDataFile);

        }
    }
    public void save(String Text,String fileName){
        FileOutputStream out =null;
        BufferedWriter writer = null;
        try{
            out = openFileOutput(fileName, Context.MODE_PRIVATE);
            writer  = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(Text);
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(writer!=null){
                    writer.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
    public String load(String fileName){
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try{
            in = openFileInput(fileName);
            reader  =new BufferedReader(new InputStreamReader(in));
            String line ="";
            while((line = reader.readLine())!=null){
                content.append(line);
            }

        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(reader!=null){
                try{
                    reader.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }
}

activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.tcm.myapplication.MainActivity">
   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       >
       <TextView
           android:layout_height="wrap_content"
           android:id="@+id/user"
           android:layout_width="0dp"
           android:layout_weight="1"
            android:layout_gravity="center"
           android:text=" 用户名:"
           android:textSize="20sp"
           />
       <EditText
           android:id="@+id/username"
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="3"
           android:hint="请输入账号"
           />
   </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/passwd"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:text="  密  码:"
            android:textSize="20sp"
            />
        <EditText
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            />
    </LinearLayout>
    <CheckBox
        android:id="@+id/remeber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="记住用户名和密码"
        android:textColor="#ff33ff"
        />

    <Button
        android:id="@+id/login"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:text="登录"
        android:background="@color/colorAccent"
        android:textColor="#ff99ff"
        />
</LinearLayout>

 

 

 

 

 

 

 

 

 

 



posted @ 2020-05-12 15:04  pickGo  阅读(525)  评论(0编辑  收藏  举报