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;//私有的,只能被创建这个文件的当前应用访问,若创建的文件已经存在,则会覆盖掉原来的文件
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;
	@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;

	}
}






版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类
XML入门的常见问题(二)
Java对象的强、软、弱和虚引用
JS解析XML文件和XML字符串详解
java中枚举的详细使用介绍
了解Xml格式
XML入门的常见问题(四)
深入SQLite多线程的使用总结详解
PlayFramework完整实现一个APP(一)
XML和YAML的使用方法
XML轻松学习总节篇