0

何人かからボイスレコードを入手しています。私は彼らにIDを与えたい。.txt新しい id 値を含むファイルを Android sdcard0に保存しようとしています。

つまり、私は新しい人のアプリケーションを開きます。プログラムは、txt ファイルから最後の ID 値を読み取ります。そして、新しい人物の ID に +1 の値を追加します。そして、.txtファイルの内容を更新します。

後でアプリケーションを閉じます。そして、もう一度アプリケーションを開き、最後の id 値を読み取り、別の人の声を person id +1 で保存します。.txtアプリケーションが開くたびに、Android sdcard0 メモリ内のファイル ID のコンテンツを動的に更新したいと考えています。

どうやってやるの?私を助けてください。これが私の簡単なコードです。

enter cod private String Load() {
String result = null;;
String FILE_NAME = "counter.txt";

    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "Records";
    File file = new File(baseDir, FILE_NAME);

   int counter = 0;
    StringBuilder text = new StringBuilder();

    try {
        FileReader fReader = new FileReader(file);
        BufferedReader bReader = new BufferedReader(fReader);
        //.....??....

        }
        result = String.valueOf(text);
    } catch (IOException e) {
        e.printStackTrace();
    }

return result;

}

4

2 に答える 2

1

私が正しく理解している場合は、アプリケーションを開くたびにテキストファイルに lastid+1 を追加する必要があります。また、このファイルを Sd カードにも保存して編集したいと考えています。

これを実行するには、次の 3 つの手順を実行します。

  1. ファイルから読み取る
  2. 最後に追加された ID を見つける
  3. 新しい ID をテキスト ファイルに書き込みます
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard, "counter.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String lastLine = "";

    while ((sCurrentLine = br.readLine()) != null) 
    {
        lastLine = sCurrentLine;
    }

    br.close();
    //Parse the string into an actual int.
    int lastId = Integer.parseInt(lastLine);


    //This will allow you to write to the file
    //the boolean true tell the FileOutputStream to append
    //instead of replacing the exisiting text
    outStream = new FileOutputStream(file, true);
    outStreamWriter = new OutputStreamWriter(outStream); 
    int newId = lastId + 1;

    //Write the newId at the bottom of the file!
    outStreamWriter.append(Integer.toString(newId));
    outStreamWriter.flush();
    outStreamWriter.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

SD カードなどの外部ストレージへの書き込みには、Android マニフェストで特別な権限が必要です。

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

そして、それはそれを行う必要があります!

参考資料については、次のリンクをご覧ください。

Androidでテキストファイルを読むにはどうすればよいですか?

Javaを使用してテキストファイルの最後の行を読み取る方法

AndroidでSDカードにテキストファイルとして保存

ファイルの末尾にテキストを追加する

于 2015-02-11T10:50:23.650 に答える
0

int 値の保存/読み込みなどの永続的なプリミティブ データが必要な場合は、Android 共有設定メカニズムを使用する必要があります: 共有設定の例

于 2015-02-11T11:19:09.823 に答える