この質問は 2 つの部分に分かれています。
InputStream i1 = new InputStream()
とはどう違いnew InputStream()
ますか?
そして、
それらを閉じるためだけにすべてのローカル変数を作成する価値はありますか?
変数を保持し、変数を使用し続け、優れたプログラマーのように入力ストリームを閉じることさえできる最初の簡単な答えを私は知っています。参照を失った秒ですが、より簡潔に見えます。2つのメモリの違いはありますか?速度差(破壊時)はどうですか?
次に、私の考えに拍車をかけた例に進みます。まず、捨てることを気にせず「new Object()」を使います。
public void getLongStrings() throws IOException {
try {
foo = FileCopyUtils.copyToString(new InputStreamReader(aBook.getInputStream()));
bar = FileCopyUtils.copyToString(new InputStreamReader(aNovel.getInputStream()));
}
catch (IOException ioe) {
//do something appropriate here;
}
}
次に、より詳細な方法について説明します
public void getLongStrings() throws IOException {
InputStream i1 = null;
InputStream i2 = null;
InputStreamReader isr1 = null;
InputStreamReader isr2 = null;
try {
i1 = aBook.getInputStream();
i2 = aNovel.getInputStream();
isr1 = new InputStreamReader(i1);
isr2 = new InputStreamReader(i2);
foo = FileCopyUtils.copyToString(isr1);
bar = FileCopyUtils.copyToString(isr2);
}
catch (IOException ioe) {
//do something appropriate here
} finally {
if (i1 != null) i1.close();
if (i2 != null) i2.close();
if (isr1 != null) isr1.close();
if (isr2 != null) isr2.close();
}
}
1回目と2回目どっちがいい?一方が他方より速いですか?きれいに見えなくても、すべてのストリームを閉じるのは賢明ですか?
洞察(または編集)をありがとう。