1

私はこの関数を持っていますが、それを呼び出しても何も返されません。

public String getfileFromSDCard(String filename){//get the file
    String text;
    text = "";

    File root = new File(Environment.getExternalStorageDirectory(), "Notes");
    if (!root.exists()) {
        root.mkdirs();
    }
    File file = new File(root,"file.txt");
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String str;

        while ((str = br.readLine()) != null) {
            text = text + str;
        }
        br.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    return text;
}

Androidマニフェスト以外に権限を追加する必要がありますか

...uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ... (コード内でこの行を書きます)

これは既に追加されており、ファイルを簡単に書き込むことができるため実行中ですが、後で読み取ることはできません

これは、onCreateから関数を呼び出す方法です

    TextView countDisplay = new TextView(this);
    CreatefiletoSDCard("testnumberone.txt","22222fkdf sdjf hjsdf sdj fsdf ");
    countDisplay.setText(getfileFromSDCard("testnumberone.txt"));

    this.setContentView(countDisplay);

ps: CreatefiletoSDCard() は機能します。

4

1 に答える 1

1

filenameメソッドでパラメーターを渡しますが、getfileFromSDCard()読み取り元の実際のファイル (名前) を にハードコーディングしたようですfile.txt。テスト ファイルの作成に使用するファイル名から推測すると、メソッドに実際に渡した名前に関係なく、存在しないファイルから読み取ろうとしている可能性があります。

つまり、おそらく次の行を変更する必要があります。

File file = new File(root,"file.txt");

に:

File file = new File(root,filename);
于 2012-04-23T00:57:52.977 に答える