0
を取得し、私は内部のファイルを開いて、このように彼への書き込み:内部ファイル(filename +「TXT」)が存在する場合内部ファイルパス
final String NEWLINE = new String(newLine+"\n");
FileOutputStream fOut = openFileOutput(fileName+".txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(NEWLINE);
私がチェックする方法が必要です。
そうでない場合は、newLineをファイルに書き込みます。それ以外の場合はを追加します。 newLineをファイルに追加します。
私が試した:
File file = getBaseContext().getFileStreamPath(fileName+".txt");
if(file.exists())...
をしかし、私は内部のファイルパスがわからない、それが働いていません。
提案がありますか?
詳細:
private void writeStringToFile(String fileName, String newLine) {
final String NEWLINE = new String(newLine + "\n");
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try { // catches IOException below
File file = getFileStreamPath(fileName + ".txt");
if (!file.exists()) {
Log.d("DAVID", "File not exist now create him");
fOut = openFileOutput(fileName + ".txt", MODE_WORLD_READABLE);
osw = new OutputStreamWriter(fOut);
} else {
Log.d("DAVID", "File already exist");
osw = new OutputStreamWriter(fOut);
}
// Write the string to the file
osw.append(NEWLINE);
// osw.write(NEWLINE);
// ensure that everything is really written out and close
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
それはそれは大丈夫だ初回実行時には - 私は取得しています:私は致命的なエラーの原因を取得しています二時間で をログに記録するために「彼を作成し、今は存在しないファイル」ヌルポインタによって。 は私がOSW
osw = new OutputStreamWriter(fOut);
FOUT
ヌル得るので、それはだと思うしかし、私はそれをどのようにを防ぐことができますか?private void apendStringToInternalFile(String fileName, String newLine)
throws FileNotFoundException, UnsupportedEncodingException,
IOException {
newLine = new String(newLine + "\n");
FileOutputStream fOut = openFileOutput(fileName + ".txt",
Context.MODE_APPEND | Context.MODE_WORLD_READABLE);
// MODE_WORLD_READABLE is _deprecated_
try {
// ALWAYS SPECIFY ENCODING -
OutputStreamWriter osw = new OutputStreamWriter(fOut, "UTF-8");
BufferedWriter buffer = new BufferedWriter(osw);
buffer.write(newLine);
buffer.flush();
} finally {
try {
fOut.close();
} catch (IOException e) {
// Log this to be on the safe side -
e.printStackTrace();
}
}
}
明らかに全体の問題は存在しない。
「うまくいきません」のような意味のない文章を入力するのではなく、症状を説明してください。 FWIW、 'getFileStreamPath()'はうまく動作するはずですが、 'getBaseContext()'は使用しません。既存の 'Context'で' getFileStreamPath() 'を呼び出すだけです。または、 'openFileOutput()'がファイルを書き込む 'File'オブジェクトを取得するために' getFilesDir() 'を使用してください。 – CommonsWare
[List](http://developer.android.com/reference/java/util/List.html)で使用したファイル名を保存し、 'if(list.contains(filename)'を参照してください。 – Phil