package gongzibai.co.cc;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.http.util.EncodingUtils;
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;
import android.widget.TextView;
public class Sample_4_1 extends Activity {
public static final String ENCODING = "UTF-8"; // 常量,
代表编码格式
String fileName = "test1.txt";// 文件的名称
TextView tv;
EditText editText1,editText2;
Button mButton;
// TextView对象引用
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);// 设置当前屏幕
// 创建文件并写入数据
// 获得从文件读入的数据
tv = (TextView) findViewById(R.id.tv);// 根据id获
取屏幕中TextView对象的引用
// 设置TextView的内容
editText1 = (EditText) findViewById
(R.id.editText1);
editText2 = (EditText) findViewById
(R.id.editText2);
mButton = (Button) findViewById(R.id.button1);
Button mButton2 = (Button) findViewById
(R.id.button2);
mButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method
stub
writeFileData(fileName,
editText1.getText().toString());
editText1.setText("");
}
});
mButton2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method
stub
String result = readFileData
(fileName);
tv.setText(result);
editText2.setText(result);
}
});
}
// 方法:向指定文件中写入指定的数据
public void writeFileData(String fileName, String
message) {
try {
FileOutputStream fout = openFileOutput
(fileName, MODE_APPEND);// 获得FileOutputStream对象
byte[] bytes = message.getBytes();// 将要
写入的字符串转换为byte数组
fout.write(bytes);// 将byte数组写入文件
fout.close();// 关闭FileOutputStream对象
} catch (Exception e) {
e.printStackTrace();// 捕获异常并打印
}
}
// 方法:打开指定文件,读取其数据,返回字符串对象
public String readFileData(String fileName) {
String result = "";
try {
FileInputStream fin = openFileInput
(fileName);// 获得FileInputStream对象
int length = fin.available();// 获取文件
长度
byte[] buffer = new byte[length];// 创建
byte数组用于读入数据
fin.read(buffer);// 将文件内容读入到byte
数组中
result = EncodingUtils.getString(buffer,
ENCODING);// 将byte数组转换成指定格式的字符串
fin.close(); // 关闭文件输入流
} catch (Exception e) {
e.printStackTrace();// 捕获异常并打印
}
return result;// 返回读到的数据字符串
}
}