最近在看黑马的视频,顺便将一些知识点记录下来,下面简单说下如何在内部存储中读写文件
我们模拟一个登陆界面,当选择记住用户名和密码选框时将它们保存下来,再次打开时将上次保存
的用户名和密码显示出来。
首先,输入用户名和密码,选择记住用户名和密码,登陆
退出之后重新打开,自动将用户名和密码显示出来
这时文件保存到了
info.txt 的大小为8,也就是我们保存的666##123
代码:
package com.th.heima;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_name = (EditText) findViewById(R.id.et_name);
et_pass = (EditText) findViewById(R.id.et_pass);
readAccount();
}
public void readAccount() {
File file = new File("data/data/com.th.heima/info.txt");
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
//把字节流转换为字符流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//读取txt文件中的用户名和密码
String text = br.readLine();
String[] s = text.split("##");
//将用户名和密码显示到相应编辑框
et_name.setText(s[0]);
et_pass.setText(s[1]);
fis.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void login(View v) {
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
CheckBox cb = (CheckBox)findViewById(R.id.cb);
//判断选框是否被勾选
if (cb.isChecked()) {
//data/data/com.th.heima:内部存储空间的路径(data/data/当前包名)
File file = new File("data/data/com.th.heima/info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write((name + "##" + pass).getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "登录成功", 0).show();
}
}
布局文件:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" >
android:id="@+id/et_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用密码"
android:inputType="textPassword" />
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="记住用户名和密码" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:onClick="login"
android:text="登录" />