05 - 数据操作一:文件读写与XML解析、SharedPreferences
文件读写核心代码 保存路径为 private final class SaveButtonClickListener implements View.OnClickListener { @Override public 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,len); } return new String(baos.toByteArray()); } } 操作模式 MODE_PRIVATE 只能被本应用使用,且覆盖原内容 1.Context.MODE_PRIVATE = 0;//私有的,只能被创建这个文件的当前应用访问,若创建的文件已经存在,则会覆盖掉原来的文件
文件保存到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(); }
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; @Override public 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.xml Editor 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.xml map.put("name",pre.getString("name","")); map.put("age",String.valueOf(pre.getInt("age",0))); return map; } }
??
??
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |