Android基础(二) 文件的读写及数据存储

一、文件的读写

public class MainActivity extends Activity {
    private EditText titleET;
	private EditText contentET;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        titleET = (EditText) findViewById(R.id.titleET);
        contentET = (EditText) findViewById(R.id.contentET);
        
    }
    
    public void save(View view){
    	try {
			String title = titleET.getText().toString();
			String content = contentET.getText().toString();
			
			FileService service = new FileService(this);
			switch (view.getId()) {
			case R.id.save2SDCardBT:
				service.save2SD(title, content);
				break;
			case R.id.save2Rom:
				service.save2Rom(title, content);
				break;
			default:
				break;
			}
			Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				Toast.makeText(this, "SD卡异常,请重新加载SD卡", Toast.LENGTH_SHORT).show();
			}
			Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
		}
    }
    
    
}
public class FileService {
	private Context context;
	
	public FileService(Context context){
		this.context=context;
	}
	
	public void save2SD(String name,String content) throws Exception{
		//获取SD卡路径
		File sdc = Environment.getExternalStorageDirectory();
		//在SD卡中创建一个路径
		File file = new File(sdc, name);
		//创建一个输出流,关联SD卡文件(如果存在就清空,不存在则创建)
		OutputStream out = new FileOutputStream(file);
		//用输出流写出数据,平台默认码表为UTF-8
		out.write(content.getBytes());
		//关闭输出流
		out.close();
		
		
		//输出总空间和可用空间
		System.out.println("totalSapce:"+file.getTotalSpace());
		System.out.println("availabeSpace:"+file.getFreeSpace());
		
	}
	
	public void save2Rom(String name,String content) throws Exception{
		OutputStream out = context.openFileOutput(name, Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
		out.write(content.getBytes());
		out.close();
	}
}

布局文件(XML):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/titleTV" />

    <EditText
        android:id="@+id/titleET"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/title_hint"
        android:inputType="text" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/contentTV" />

    <EditText
        android:id="@+id/contentET"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/content_hint"
        android:inputType="textMultiLine"
        android:lines="3" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/save2SDCardBT"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="save"
            android:text="@string/save2SD_text" />

        <Button
            android:id="@+id/save2Rom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="save"
            android:text="@string/save2Rom_text" />
    </LinearLayout>
</LinearLayout>

image

1.写文件到SD卡:

    使用IO流写出数据时,需要注意文件的路径。

    由于不同版本Android系统SD卡的路径可能不同,建议使用Environment.getExternalStorageDirectory()方法来获取文件的路径。

    如果需要判断SD卡的状态,可以使用Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

    注意:将文件写入SD卡需要在清单列表中配置权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

2.写文件到手机机身内存

    使用Context类的openFileOutput()方法可以在当前应用所在文件夹打开一个输出流,关联指定的文件。openFileOutput()方法可以指定文件模式MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE,MODE_APPEND。

    注意:使用openFileOutput()方法写入到机身内存的文件,会随着应用的卸载而删除。而存放在SD卡的文件则可以长久保存。

 

二、XML的Pull解析

public class Person {
	private Integer id;
	private String name;
	private Integer age;
	public Person() {
		super();
	}
	public Person(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
}
public class PersonService {

	/**
	 * 通过一个关联了XML文件的输出流,解析出一个List集合,其中包含若干Person对象
	 * @param in	关联XML文件的输入流
	 * @return	返回一个包含Person对象的List集合,如果输入流关联的XML文件中不包含Person数据,则得到一个size=0的集合
	 * @throws Exception
	 */
	public List<Person> getPersons(InputStream in) throws Exception {
		List<Person> persons = new ArrayList<Person>();
		Person p = null;

		XmlPullParser parser = Xml.newPullParser();//得到解析器对象
		parser.setInput(in,"UTF-8");//设置输入流

		for (int type = parser.getEventType(); type != XmlPullParser.END_DOCUMENT; type = parser
				.next()) {//解析XML创建Person对象,装入集合
			if (type == XmlPullParser.START_TAG) {//如果是开始标签事件
				if ("person".equals(parser.getName())) {//开始的是person
					p = new Person();
					String id = parser.getAttributeValue(0);//获取属性
					p.setId(Integer.parseInt(id));
					persons.add(p);
				} else if ("name".equals(parser.getName())) {
					String name = parser.nextText();//获取文本
					p.setName(name);
				} else if ("age".equals(parser.getName())) {
					String age = parser.nextText();
					p.setAge(Integer.parseInt(age));
				}
			}
		}

		return persons;//返回集合
	}
	
	/**
	 * 向指定的输出流写出XML数据,XML数据为指定集合中的Person信息
	 * @param out	指定的输出流
	 * @param persons	要写出的集合
	 * @throws Exception
	 */
	public void writePersons(OutputStream out,List<Person> persons) throws Exception{
		XmlSerializer serializer = Xml.newSerializer();//获取序列化工具
		serializer.setOutput(out,"UTF-8");//设置输出流
		
		serializer.startDocument("UTF-8", true);//开始文档
		serializer.startTag(null, "persons");//开始标签
		
		for (Person person : persons) {
			serializer.startTag(null, "person");
			serializer.attribute(null, "id", person.getId().toString());//设置属性
			
			serializer.startTag(null, "name");
			serializer.text(person.getName());//设置文本
			serializer.endTag(null, "name");
			
			serializer.startTag(null, "age");
			serializer.text(person.getAge().toString());
			serializer.endTag(null, "age");
			
			serializer.endTag(null, "person");
		}
		
		serializer.endTag(null, "persons");//结束标签
		serializer.endDocument();//结束文档
	}

}
public class PersonServiceTest extends AndroidTestCase {
	
	public void testGetPersons() throws Exception{
		PersonService service = new PersonService();
		
		InputStream in = PersonServiceTest.class.getClassLoader().getResourceAsStream("persons.xml");
		List<Person> persons = service.getPersons(in);
		in.close();
		
		for (Person person : persons) {
			System.out.println(person);
		}
		
		
		OutputStream out = new FileOutputStream("/mnt/sdcard/persons.xml");
		persons.add(new Person(4, "xxx", 24));
		persons.add(new Person(4, "Lucas", 24));
		service.writePersons(out, persons);
	}
	
}

三、SharedPreferences

public class MainActivity extends Activity {
    private EditText nameET;
	private EditText phoneET;
	private EditText emailET;
	private SharedPreferences sp;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //获取3个EditText
        nameET = (EditText) findViewById(R.id.nameET);
        phoneET = (EditText) findViewById(R.id.phoneET);
        emailET = (EditText) findViewById(R.id.emailET);
        
        sp = this.getSharedPreferences("config",MODE_PRIVATE);
        
        //获取以前存储的数据,把数据放到EditText中
        nameET.setText(sp.getString("name", ""));
        phoneET.setText(sp.getString("phone", ""));
        emailET.setText(sp.getString("email", ""));
    }
    
    public void save(View view){
    	String name=nameET.getText().toString();
    	String phone=phoneET.getText().toString();
    	String email=emailET.getText().toString();
    	
    	//用SharedPreferences存储数据
    	Editor editor=sp.edit();
    	editor.putString("name", name);
    	editor.putString("phone", phone);
    	editor.putString("email", email);
    	editor.commit();
    	
    	//弹出提示
    	Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }
}

布局文件(XML):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/nameTV" />
    <EditText
        android:id="@+id/nameET"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        />
    
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/phoneTV" />
    <EditText
        android:id="@+id/phoneET"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:inputType="phone"
        />
    
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/emalTV" />
    <EditText
        android:id="@+id/emailET"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        />
    <Button
        android:id="@+id/saveBT"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="@string/save2Default"
        
        android:onClick="save"
        />

</LinearLayout>

1.什么是SharedPreferences

    它是一个Map集合,可以持久化存储数据,通常用来保存程序中的一些键值对数据。

2.怎么使用SharedPreferences

    Context类可以调用getSharedPreferences()方法来得到SharedPreferences的对象。获取数据的时候则直接调用getString(),getInt()等方法。

    在设置数据的时候,需要先调用SharedPreferences.edit()方法得到一个Editor对象,然后使用putString(),putInt()等方法,最后使用Editor.commit()方法进行提交。

image

posted on 2013-04-19 19:04  foolchen  阅读(269)  评论(0编辑  收藏  举报

导航