1

我正在尝试在 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();
}
}
});
}
}

`

为什么它不工作?提前感谢您的帮助。任何解释将不胜感激。

4

1 回答 1

5

用作new File("text1.txt")输出在 Android 上不起作用。当前的工作目录始终/对您的应用程序不可写。利用

File f = new File(Environment.getExternalStorageDirectory(), "text1.txt");

getExternalStorageDirectory()是新手机的内部存储。

如果您想将数据存储在您的应用程序私有文件夹中,您的应用程序上下文有几个可以使用的路径。来自的路径Environment位于公共场所,您可以使用文件管理器轻松读取数据

不要忘记添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如果您想写入这些公共路径

于 2012-11-22T02:22:47.383 回答