05 - 数据操作一:文件读写与XML解析、SharedPreferences

来源:互联网 发布:微盘交易源码 阴极铜 编辑:程序博客网 时间:2024/06/05 04:24

文件读写核心代码  保存路径为

private final class SaveButtonClickListener implements View.OnClickListener {@Overridepublic void onClick(View v) {EditText fileName = (EditText) findViewById(R.id.fileName);EditText fileContent = (EditText) findViewById(R.id.fileContent);String fileNameStr = fileName.getText().toString();String fileContentStr = fileContent.getText().toString();FilesService fileSer = new FilesService(getApplicationContext());try {fileSer.save(fileNameStr, fileContentStr);Toast.makeText(getApplicationContext(), R.string.saveSuccess, 2).show();} catch (Exception e) {Toast.makeText(getApplicationContext(), R.string.saveFaile, 2).show();}}

文件操作  String path = "/data/data/com.yza.app/files/t.txt";     “t.txt” 与fileNameStr 一样

getFilesDir() 获取当前应用files目录

getCacheDir() 获取当前应用cache目录


public class FilesService {private Context context;public FilesService(Context context) {super();this.context = context;} public void save(String fileNameStr, String fileContentStr)throws Exception {// 操作模式 MODE_PRIVATE 只能被本应用使用,且覆盖原内容 FileOutputStream fos = context.openFileOutput(fileNameStr,Context.MODE_PRIVATE);fos.write(fileContentStr.getBytes());fos.close();} public String read(String fileNameStr) throws Exception {FileInputStream fis = context.openFileInput(fileNameStr);ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = fis.read(buffer)) != -1) {baos.write(buffer, 0, len);}return new String(baos.toByteArray()); } }

操作模式 MODE_PRIVATE 只能被本应用使用,且覆盖原内容

1.Context.MODE_PRIVATE = 0;//私有的,只能被创建这个文件的当前应用访问,若创建的文件已经存在,则会覆盖掉原来的文件
2.Context.MODE_APPEND = 32768;//若文件不存在也会创建,若文件存在则在文件的末尾进行追加内容,也是私有的
3.Context.MODE_WORLD_READABLE=1;//创建出来的文件可以被其他应用所读取
4.Context.MODE_WORLD_WRITEABLE=2//允许其他应用对其进行写入。
当然,这几种模式也可以混用,比如允许其他应用程序对该文件进行读写,则可以是
FileOutputStream outStream = this.openFileOutput("itcast.txt",Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);


该方式默认为覆盖原有的文件,即如果再次对该文件写入内容,则会覆盖掉itcast.txt的原有内容,如果想要实现追加并能被其他应用程序访问,则应该设置以下模式:
FileOutputStream outStream = this.openFileOutput("itcast.txt",Context.MODE_APPEND+Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);

文件保存到SDCard:

public void saveToSDCard(String fileName,String content)throws Exception{File file = new File(new File("/mnt/sdcard"),fileName);FileOutputStream fos = new FileOutputStream(file);fos.write(content.getBytes());fos.close();}


推荐使用API的路径:        File file =  new File(Environment.getExternalStorageDirectory(),fileName);

 <!-- sdcard 创建与删除的权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- sdcard 存储权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

XML解析


解析的核心代码

public class PersonService {public static List<Person> getPersonList(InputStream xml) throws Exception {List<Person> plist = null;Person p = null;XmlPullParser pullParser = Xml.newPullParser();pullParser.setInput(xml, "UTF-8");// 设置要解析的XMl数据int event = pullParser.getEventType();Log.i("person", "进入解析");while (event != XmlPullParser.END_DOCUMENT) {switch (event) {case XmlPullParser.START_DOCUMENT:plist = new ArrayList<Person>();break;case XmlPullParser.START_TAG:if ("person".equals(pullParser.getName())) {p = new Person();p.setId(Integer.parseInt(pullParser.getAttributeValue(0)));}if ("name".equals(pullParser.getName())) {p.setName(pullParser.nextText());}if ("age".equals(pullParser.getName())) {p.setAge(Integer.parseInt(pullParser.nextText()));}break;case XmlPullParser.END_TAG:if ("person".equals(pullParser.getName())) {plist.add(p);p = null;}break;}event = pullParser.next();}return plist;}}

<?xml version="1.0" encoding="UTF-8"?><persons><person id="22"><name>zhangsan</name><age>20</age></person><person  id="24"><name>lisi</name><age>15</age></person></persons>

public void testA() throws Exception {Log.i("person", "PersonService");InputStream xml = this.getClass().getClassLoader().getResourceAsStream("person.xml"); Log.i("person", "12"+(xml==null));List<Person> l = PersonService.getPersonList(xml);for (Person p : l) {Log.i("person", p.getName());} }


保存


public void saveXML(List<Person> list, OutputStream out) throws Exception {XmlSerializer xs = Xml.newSerializer();xs.setOutput(out, "UTF-8");xs.startDocument("UTF-8", true);xs.startTag(null, "persons");  //不需要命名空间for (Person p : list) {xs.startTag(null, "person");xs.attribute(null, "id", p.getId().toString()); xs.startTag(null, "name");xs.text(p.getName());xs.endTag(null, "name"); xs.startTag(null, "age");xs.text(p.getAge().toString());xs.endTag(null, "age"); xs.endTag(null, "person");} xs.endTag(null, "persons"); xs.endDocument(); out.flush();out.close();}

SharedPreferences

public class ShareprefarActivity extends Activity {private EditText name;private EditText age;private PreferencesService ps;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);name = (EditText) this.findViewById(R.id.nameText);age = (EditText) this.findViewById(R.id.ageText);ps= new PreferencesService(getApplicationContext());Map<String, String> map =ps.read();name.setText(map.get("name"));age.setText(map.get("age"));}public void save(View v){     System.out.println(ps==null);     System.out.println(age.getText().toString());     System.out.println(age.getText().toString());    ps.save(name.getText().toString(),Integer.valueOf(age.getText().toString()));    Toast.makeText (getApplicationContext(), "成功保存", 1).show();    }}


public class PreferencesService {private Context context;public PreferencesService(Context context) {this.context = context;}public void save(String name, Integer age) {SharedPreferences pre = context.getSharedPreferences("yza",Context.MODE_PRIVATE);// 默认后缀xml yza.xmlEditor edit = pre.edit();edit.putString("name", name);edit.putInt("age", age);edit.commit();}// 获取参数public Map<String, String> read() {Map<String, String> map = new HashMap<String, String>();SharedPreferences pre = context.getSharedPreferences("yza",Context.MODE_PRIVATE);// 默认后缀xml yza.xmlmap.put("name", pre.getString("name", ""));map.put("age", String.valueOf(pre.getInt("age", 0)));return map;}}





0 0