package xdglyt.software.jhwz.myapplication11;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
public class FileSaveClass {
public static boolean saveUserInfo(Context context,String username,String password){
try {
FileOutputStream fos = context.openFileOutput("data.txt",Context.MODE_PRIVATE);
fos.write((username+":"+password).getBytes());
fos.close();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
public static Map<String,String> getUserInfo(Context context){
String content = "";
try {
FileInputStream fis = context.openFileInput("data.txt");
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
content = new String(buffer);
Map<String,String> userInfo = new HashMap<String,String>();
String[] infos = content.split(":");
userInfo.put("username",infos[0]);
userInfo.put("password",infos[1]);
fis.close();
return userInfo;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package xdglyt.software.jhwz.myapplication11;
import androidx.appcompat.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 org.w3c.dom.Text;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText et1;
private EditText et2;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText)findViewById(R.id.et_username);
et2 = (EditText)findViewById(R.id.et_password);
btn = (Button)findViewById(R.id.button);
Map<String,String>userInfo =FileSaveClass.getUserInfo(this);
if(userInfo!=null){
et1.setText(userInfo.get("username"));
et2 .setText(userInfo.get("password"));
}
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = et1.getText().toString();
String password = et2.getText().toString();
if(TextUtils.isEmpty(name)){
Toast.makeText(MainActivity.this,"请输入用户名!",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(MainActivity.this,"请输入密码!",Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(MainActivity.this,"登陆成功!",Toast.LENGTH_LONG).show();
boolean isSaveSuccess = FileSaveClass.saveUserInfo(MainActivity.this,name,password);
if (isSaveSuccess){
Toast.makeText(MainActivity.this,"保存成功!",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"保存失败!",Toast.LENGTH_LONG).show();
}
}
});
}
}