我正在尝试在 android 上测试一个简单的文件 i/o 程序,我在 EditText 中输入一些文本,当我单击“保存”按钮时,它会将内容写入文件中。当我单击加载按钮时,它会将内容加载回 EditText。
这是我的代码---
public class Activity2 extends Activity {
private EditText textBox;
private static final int READ_BLOCK_SIZE = 100;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
textBox = (EditText) findViewById(R.id.txtText1);
Button saveBtn = (Button) findViewById(R.id.btnSave);
Button loadBtn = (Button) findViewById(R.id.btnLoad);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = textBox.getText().toString();
try
{
PrintWriter PR=new PrintWriter(new File("text1.txt"));
PR.write(str);
PR.flush();
PR.close();
//textBox.setText("");
//---display file saved message---
Toast.makeText(getBaseContext(),
"File saved successfully!",
Toast.LENGTH_SHORT).show();
//---clears the EditText---
textBox.setText("");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try
{
File f=new File("text1.txt");
BufferedReader BR=new BufferedReader(new FileReader(f));
String txt="";
String str;
while((str=BR.readLine())!=null)
{
txt+=str;
}
//---set the EditText to the text that has been
// read---
textBox.setText(txt);
BR.close();
Toast.makeText(getBaseContext(),
"File loaded successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
}
}
`
为什么它不工作?提前感谢您的帮助。任何解释将不胜感激。