public class MainActivity extends Activity {
EditText text;
TextView content;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.editText);
content = (TextView) findViewById(R.id.contentView);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WriteFile(text.getText().toString());
content.setText(ReadFile());
}
});
}
public void WriteFile(String content) {
try {
//获取文件的输出流,若没有该文件则会自动创建
FileOutputStream fos = openFileOutput("a.txt", MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String ReadFile() {
StringBuffer content = new StringBuffer();
try {
//创建一个输入流
BufferedReader br=new BufferedReader(new InputStreamReader(openFileInput("a.txt")));
String line = null;
while((line=br.readLine())!=null){
//拼接后加入换行符
content.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
Android程序:程序中的文件读写实例
最新推荐文章于 2020-08-21 08:32:33 发布