0

私のアプリには3つのEditTextがあります。このEditTextsのコンテンツをファイルに書き込みたいのですが、filewriteはnullpointer例外をスローします。なんで?

OutputStream f1;グローバルに宣言されます。

BtnSave = (Button)findViewById(R.id.Button01);
BtnSave.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        intoarray =   name + "|" + number + "|" + freq + "\n";
        Toast.makeText(Main.this, "" + intoarray, Toast.LENGTH_SHORT).show();
        //so far so good
          byte buf[] = intoarray.getBytes(); 

          try {
            f1 = new FileOutputStream("file2.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
          try {
            f1.write(buf);  //nullpointer exception
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
          try {
            f1.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
4

3 に答える 3

0

あなたが私を助けようとしていたすべてのために申し訳ありません、私は間違った質問をしました。内部ストレージを使用したかった(そして現在は機能している)。問題が何であるかはわかりませんが、以下のコード(私がよく使用している)のファイル書き込みは問題ありません:

try {
    File root = Environment.getExternalStorageDirectory();
    File file = new File(root, "Data.txt");
    if (root.canWrite()) {
        FileWriter filewriter = new FileWriter(file, true);
        BufferedWriter out = new BufferedWriterfilewriter);
        out.write(intoarray);
        out.close();
    }
} catch (IOException e) {
    Log.e("TAG", "Could not write file " + e.getMessage());
}

できればトピックを削除します。トピックを閉じるためにこの回答を受け入れます。

とにかくありがとう。

于 2011-09-06T10:08:53.977 に答える
0

最も可能性が高い

f1 = new FileOutputStream("file2.txt");

失敗し、例外をキャッチしたため、f1はnullのままでした。ほとんどの場合、Androidでは、アプリケーションデータディレクトリまたは外部ストレージのいずれかにのみファイルを作成できます。

于 2011-07-25T22:44:17.340 に答える
0

現在これを使用している方法は機能しません。通常、内部ストレージに書き込もうとしています。内部ストレージはアプリ専用であり、アプリケーションディレクトリ内に含まれている必要があります。

ファイルストリームを作成する適切な方法は次のとおりです。

fin  = openFileOutput("file2.txt", Context.MODE_PRIVATE); // open for writing
fout = openFileInput("file2.txt", Context.MODE_PRIVATE);  // open for reading 

これにより、アプリケーションのストレージ領域にファイルが配置されます。これは通常、次のようなものです。

/data/data/com.yourpackagename/files/...

もちろんディレクトリ構造が必要な場合でも、アプリケーション領域内にディレクトリを作成できます。

別のプロセスである外部ストレージに書き込む必要がある場合、詳細については、Androidデータストレージを参照してください。

于 2011-07-26T00:19:30.247 に答える