は、私はこのコードのスニペットを持っている:FileWriterは書きませんか?
私はranit、それは文字列sequence
と
mySink
内部のそれのインデックスを印刷
try {
f1 = new File("sink.txt");
f1.createNewFile();
fw = new FileWriter(f1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
... code ...
System.out.println(sequence);
System.out.println(mySink.indexOf(sequence));
String result = "";
int firstIndex = mySink.indexOf(sequence);
if (firstIndex >= 0) {
System.out.println(true);
int secondIndex = mySink.indexOf(sequence, firstIndex + sequence.length());
if (secondIndex >= 0) {
System.out.println(true);
result = mySink.substring(firstIndex, secondIndex + sequence.length());
System.out.println(result);
}
}
try { // Write it to file
fw.write(result);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("done");
。その後、if文の中に入り、2つのtrue
を印刷してresult
を印刷したので、は正常に初期化されています。しかし、私がファイルsink.txt
を見ると、それは空白だと分かります。なぜそれがこのように動作していますか?私のコードで何かが恋しいですか?それは前に働いていたし、もう少しコードを追加しました。私はプログラムの実行中にFileWriter
またはFile
に触れることはありません。前もって感謝します!
これが私の出力であるあなたが見たい場合:
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 98, 48, 43, 47, 89]
2000466
true
true
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 98, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 59, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 81, 59, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 81, 98, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 98, 48, 43, 47, 89]
done
あなたは 'FileWriter'を終了していません。 'fw.close()' –
フォローアップ:ファイルを開くときにtry-with-resourcesを使うと、常に正しく閉じられます。 – Andreas
try-catchブロックを削除します。例外をキャッチしてそれを無視する、すなわち、次のコードが実行を継続できるようにすると、カスケード障害が発生するだけです。例:ファイルを作成/置換できない場合、 'IOException'が発生し、' fw'は決して割り当てられません。 'fw.write(result)'は 'NullPointerException'で失敗します。このエラーは原因を誤解させることになります。 – Andreas