Android下用txt保存用户信息。
@SuppressLint("SdCardPath") private boolean saveUserInfo(){
Context context = this;
File file = null;
FileOutputStream fos = null;
try {
file = new File(context.getCacheDir(),"info.txt");
//file = new File(context.getFileDir(),"info.txt");
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (checkBox.isChecked()) {
if (file.exists()) {
fos.write((username+"##"+password).getBytes());
} else {
fos.write((username+"##"+password).getBytes());
}
} else {
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
/*
* 然后在onCreate中添加回显
* Map<String , String> map = getSavedUserInfo(this);
* if(map != null){
* username.setText(map.get("username"));
* password.setText(map.get("pasword"));
* }
*
*/
public static Map<String, String> getSavedUserInfo(Context context){
File file = new File(context.getCacheDir(),"info.txt");
/*
* 也可以用
* content.openFileOutput();来创建
* 特别是Content创建的安全性可以控制。
*/
try {
FileInputStream fis = new FileInputStream(file);
@SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String str = br.readLine();
String[] info = str.split("##");
Map<String, String> map = new HashMap<String, String>();
map.put("username", info[0]);
map.put("password", info[1]);
return map;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
FileOutputStream openFileOutput (String name, int mode)
作用:可以方便地再手机中创建文件,并返回文件输出流,用于对文件做写入操作。
name:
用于指定文件名称,不能包含路径分隔符“/”,如果文件不存在,Android会自动创建它。创建的文件保存在/data/data/<package name>/files/目录中。如:/data/data/GH.Test/files/abc.txt
mode取值:
MODE_APPEND 私有(只有创建此文件的程序能够使用,其他应用程序不能访问),在原有内容基础上增加数据
MODE_PRIVATE 私有,每次打开文件都会覆盖原来的内容
MODE_WORLD_READABLE 可以被其他应用程序读取
MODE_WORLD_WRITEABLE 可以被其他应用程序写入
另:1.FileInputStream openFileInput (String name)
返回文件输入流,用于对文件的读操作。
2. Activity还提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data/<package name>/cache目录
getFilesDir()方法用于获取/data/data/<package name>/files目录
更多的情况主要是用SharedPreferences方法来保存。
public class MainActivity extends ActionBarActivity implements OnClickListener {
private String username = null;
private String password = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etUsername = (EditText) this.findViewById(R.id.inputUserName);
EditText etPasswrod = (EditText) this.findViewById(R.id.Password);
Button btLogin = (Button) this.findViewById(R.id.login);
username = etUsername.getText().toString().trim();
password = etPasswrod.getText().toString().trim();
btLogin.setOnClickListener(this);
SharedPreferences sp = this.getSharedPreferences("config", MODE_PRIVATE);
String defaultUsername = sp.getString("username", "");
etUsername.setText(defaultUsername);
String defaultPassword = sp.getString("password", "");
etPasswrod.setText(defaultPassword);
}
public void saveUserInfo(Context context, String username,
String password) {
//在手机的相应目录下保存config.xml文件.以Map格式储存。
SharedPreferences sp = context.getSharedPreferences("config",
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
Toast.makeText(this, "写入成功", 0).show();
}
@Override
public void onClick(View v) {
saveUserInfo(this, username, password);
Toast.makeText(this, "登陆成功", 0).show();
}
}
XML文件的序列化
用XML文件保存短信信息。
SmsInfo.java
package com.example.domain;
public class SmsInfo {
private long date;
private int type;
private String body;
private String address;
public SmsInfo() {
super();
// TODO Auto-generated constructor stub
}
public SmsInfo(long date, int type, String body, String address) {
super();
this.date = date;
this.type = type;
this.body = body;
this.address = address;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
SmsInfo2.java
package com.example.domain;
public class SmsInfo2 {
private long date;
private int type;
private String body;
private String address;
private int id;
public SmsInfo2() {
super();
// TODO Auto-generated constructor stub
}
public SmsInfo2(long date, int type, String body, String address,int id) {
super();
this.date = date;
this.type = type;
this.body = body;
this.address = address;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
MainActivity.java
package com.example.sharedpreferences;
import com.example.domain.SmsInfo;
import com.example.domain.SmsInfo2;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private String username = null;
private String password = null;
private List<SmsInfo> smsinfos;
private List<SmsInfo2> smsInfo2s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etUsername = (EditText) this.findViewById(R.id.inputUserName);
EditText etPasswrod = (EditText) this.findViewById(R.id.Password);
Button btLogin = (Button) this.findViewById(R.id.login);
Button btBackupMsm = (Button) this.findViewById(R.id.backupMsm);
Button btBackupMsm2 = (Button) this.findViewById(R.id.backupMsm2);
username = etUsername.getText().toString().trim();
password = etPasswrod.getText().toString().trim();
btLogin.setOnClickListener(this);
btBackupMsm.setOnClickListener(this);
btBackupMsm2.setOnClickListener(this);
SharedPreferences sp = this
.getSharedPreferences("config", MODE_PRIVATE);
String defaultUsername = sp.getString("username", "");
etUsername.setText(defaultUsername);
String defaultPassword = sp.getString("password", "");
etPasswrod.setText(defaultPassword);
smsinfos = new ArrayList<SmsInfo>();
smsInfo2s = new ArrayList<SmsInfo2>(null);
Random random = new Random();
long number = 1350000001;
for (int i = 0; i < 10; i++) {
smsinfos.add(new SmsInfo(System.currentTimeMillis(), random
.nextInt(2) + 1, ":短信内容", Long.toString(number + i)));
}
for (int i = 0; i < 10; i++) {
smsInfo2s.add(new SmsInfo2(System.currentTimeMillis(), random
.nextInt(2) + 1, ":短信内容", Long.toString(number + i), i));
}
}
public void saveUserInfo(Context context, String username, String password) {
// 在手机的相应目录下保存config.xml文件.以Map格式储存。
SharedPreferences sp = context.getSharedPreferences("config",
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
}
public void backupMsm(View v) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" endcoding=\"utf-8\"?>");
sb.append("<smss>");
for (int i = 0; i < smsinfos.size(); i++) {
sb.append("<sms>");
sb.append("<address>");
sb.append(smsinfos.get(i).getAddress());
sb.append("</address>");
sb.append("<type>");
sb.append(smsinfos.get(i).getType());
sb.append("</type>");
sb.append("<body>");
sb.append(smsinfos.get(i).getBody());
sb.append("</body>");
sb.append("<date>");
sb.append(smsinfos.get(i).getDate());
sb.append("</date>");
sb.append("</sms>");
}
sb.append("smss");
try {
File file = new File(Environment.getExternalStorageDirectory(),
"backup2.xml");
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
Toast.makeText(this, "备份成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "备份失败", Toast.LENGTH_SHORT).show();
// TODO: handle exception
}
}
public void backupMsm2(View v) {
XmlSerializer serializer = Xml.newSerializer();
try {
File file = new File(Environment.getExternalStorageDirectory(),
"backup2.xml");
FileOutputStream fos = new FileOutputStream(file);
//初始化 序列号器 指定xml文件写入到哪个文件 并制定文件的编码,
serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "smss");
for (int i = 0; i < smsInfo2s.size(); i++) {
serializer.startTag(null, "sms");
serializer.attribute(null, "id", smsInfo2s.get(i).getId()+"");
serializer.startTag(null, "body");
serializer.text(smsInfo2s.get(i).getBody());
serializer.endTag(null, "body");
serializer.startTag(null, "address");
serializer.text(smsInfo2s.get(i).getAddress() + "");
serializer.endTag(null, "address");
serializer.startTag(null, "type");
serializer.text(smsInfo2s.get(i).getType() + "");
serializer.endTag(null, "type");
serializer.startTag(null, "date");
serializer.text(smsInfo2s.get(i).getDate() +"");
serializer.endTag(null, "date");
serializer.endTag(null, "sms");
}
serializer.endTag(null, "smss");
fos.close();
Toast.makeText(this, "备份成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "备份失败", Toast.LENGTH_SHORT).show();
// TODO: handle exception
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
saveUserInfo(this, username, password);
Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
break;
case R.id.backupMsm:
backupMsm(v);
case R.id.backupMsm2:
backupMsm2(v);
default:
break;
}
}
}
SmsInfo的方式更加健壮。
采用pull解析xml文件
weather.xml
<?xml version="1.0" encoding="utf-8"?>
<infos>
<city id="1">
<temp>20℃/30℃</temp>
<weather>2014年12月2日1 多云转阴</weather>
<wind>南风三级3-4级</wind>
<name>上海</name>
<pm>200</pm>
</city>
<city id="2">
<temp>24℃/35℃</temp>
<weather>2014年12月2日1 多云转阴</weather>
<wind>南风三级1-4级</wind>
<name>北京</name>
<pm>500</pm>
</city>
<city id="3">
<temp>23℃/34℃</temp>
<weather>2014年12月2日1 多云转阴</weather>
<wind>南风三级2-4级</wind>
<name>广州</name>
<pm>400</pm>
</city>
<city id="4">
<temp>20℃/30℃</temp>
<weather>2014年12月2日1 多云转阴</weather>
<wind>南风三级3-5级</wind>
<name>深圳</name>
<pm>300</pm>
</city>
</infos>
WeatherInfos.java
package com.example.weather.domain;
public class WeatherInfos {
private int id;
private String name;
private String pm;
private String weather;
private String temp;
private String wind;
public WeatherInfos() {
super();
// TODO Auto-generated constructor stub
}
public WeatherInfos(int id, String name, String pm, String weather,
String temp, String wind) {
super();
this.id = id;
this.name = name;
this.pm = pm;
this.weather = weather;
this.temp = temp;
this.wind = wind;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPm() {
return pm;
}
public void setPm(String pm) {
this.pm = pm;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
@Override
public String toString() {
return "WeatherInfos [id=" + id + ", name=" + name + ", pm=" + pm
+ ", weather=" + weather + ", temp=" + temp + ", wind=" + wind
+ "]";
}
}
WeatherService.java
/**
*
*/
/**
* @author DoItYouself
*
*/
package com.example.weather.server;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;
import com.example.weather.domain.WeatherInfos;
public class WeatherService {
public static ArrayList<WeatherInfos> getWeatherInfos(InputStream is) throws Exception{
XmlPullParser parser = Xml.newPullParser();
//初始化解析器
parser.setInput(is, "utf-8");
WeatherInfos weatherInfo = null;
ArrayList<WeatherInfos> weatherInfos = null;
int type = parser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("infos".equals(parser.getName())) {
//解开全局开始标签
weatherInfos = new ArrayList<WeatherInfos>();
} else if("city".equals(parser.getName())) {
weatherInfo = new WeatherInfos();
String idStr = parser.getAttributeValue(0);
weatherInfo.setId(Integer.parseInt(idStr));
} else if("temp".equals(parser.getName())) {
String temp = parser.nextText();
weatherInfo.setTemp(temp);
} else if("weather".equals(parser.getName())) {
String weather = parser.nextText();
weatherInfo.setWeather(weather);
} else if("wind".equals(parser.getName())) {
String name = parser.nextText();
weatherInfo.setName(name);
} else if("pm".equals(parser.getName())) {
String pm = parser.nextText();
weatherInfo.setPm(pm);
}
break;
case XmlPullParser.END_TAG:
if ("city".equals(parser.getName())) {
weatherInfos.add(weatherInfo);
weatherInfo = null;
}
break;
default:
break;
}
type = parser.next();
}
return weatherInfos;
}
}
MainActivity.java
package com.example.weather;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.widget.Toast;
import com.example.weather.domain.WeatherInfos;
import com.example.weather.server.WeatherService;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) this.findViewById(R.id.tv);
try {
ArrayList<WeatherInfos> infos = WeatherService
.getWeatherInfos(MainActivity.class.getClassLoader()
.getResourceAsStream("weather.xml"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < infos.size(); i++) {
String str = infos.get(i).toString();
sb.append(str);
sb.append("\n");
}
tv.setText(sb.toString());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "解析失败", Toast.LENGTH_SHORT);
// TODO: handle exception
}
}
}