Android文件读写简单示例

界面如下


Android文件读写简单示例

package org.snailteam;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class FileSave extends Activity {
	private EditText text;
	private Button save, reader;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.fileui);
		text = (EditText) findViewById(R.id.editText1);
		save = (Button) findViewById(R.id.buttonSave);
		reader = (Button) findViewById(R.id.reader);
		save.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				OutputStream os = null;
				try {
					os = openFileOutput("textMe", MODE_PRIVATE);
					os.write(text.getText().toString().getBytes());
				} catch (FileNotFoundException e) {

				} catch (IOException e) {

				} finally {
					try {
						os.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				text.setText("");
			}
		});
		reader.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				text.setText("");
				InputStream is = null;
				byte[] b = null;
				try {
					is = openFileInput("textMe");
					b = new byte[1024];
					int length = is.read(b);
					text.setText(new String(b));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					try {
						is.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
	}

}