1

EditTextにテキストを入力し、[保存]ボタンをクリックすると、コンテンツがファイルに書き込まれる、Androidで単純なファイルI/Oプログラムをテストしようとしています。[ロード]ボタンをクリックすると、コンテンツが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 に答える