package com.example.test_of_file2;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
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 MainActivity extends Activity {
private EditText editText;
private Button button1, button2;
private TextView textView;
public static final String FILENAME = "test.txt";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取界面控件
findView();
// 保存监听
button1.setOnClickListener(saveListener);
// 读取监听
button2.setOnClickListener(readListener);
}
// 获取界面控件的方法
public void findView() {
editText = (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView1);
}
// 保存监听事件
OnClickListener saveListener= new OnClickListener() {
public void onClick(View v) {
writeFile(editText.getText().toString());
textView.setText(readFile());
}
};
// 读取监听事件
OnClickListener readListener = new OnClickListener() {
public void onClick(View v) {
textView.setText(readFile());
}
};
// 写文件
public void writeFile(String content) {
try {
// 打开流
FileOutputStream outputStream = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
// 进行写操作
outputStream.write(content.getBytes());
// 关闭流
outputStream.close();
} catch (Exception e) {
// 将错误打印在控制台上
e.printStackTrace();
}
}
// 读文件
public String readFile() {
String content = null;
try {
// 打开流
FileInputStream fileInputStream = openFileInput(FILENAME);
// 读取
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
//将输入流中的数据读到buffer数组中
while ((len=fileInputStream.read(buffer))!= -1) {
//将len个字节的数据写入到buffer数组中
byteArrayOutputStream.write(buffer, 0, len);
}
//将缓冲区的内容转换为字符串
content = byteArrayOutputStream.toString();
// 关闭流
byteArrayOutputStream.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
}