Skip to content

Instantly share code, notes, and snippets.

@Kanasansoft
Created February 24, 2012 18:11
Show Gist options
  • Save Kanasansoft/1902497 to your computer and use it in GitHub Desktop.
Save Kanasansoft/1902497 to your computer and use it in GitHub Desktop.
package com.kanasansoft.CloseableUtility;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public abstract class CloseableUtility {
public CloseableUtility(Closeable... closeables) throws IOException {
main();
closeAll(closeables);
}
abstract public void main() throws IOException;
private void closeAll(Closeable... closeables) throws IOException {
closeAll(Arrays.asList(closeables));
}
private void closeAll(List<Closeable> closeables) throws IOException {
if (closeables.isEmpty()) {
return;
}
try {
if (closeables.get(0) != null) {
closeables.get(0).close();
}
} catch (IOException e) {
throw e;
} finally {
closeAll(closeables.subList(1, closeables.size()));
}
}
}

Streamを安全にcloseするためのアイディア その3

概要

mainメソッドからエンクロージングクラスの変数を参照する

欠点

  • 変数を参照する場合、finalが強要される
    • エンクロージングクラスのフィールドならOK
  • 実行順を強制できる以外は、利便性はその1とあまり変わらない
    • その1よりも複雑なため利点が薄れる
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.kanasansoft.CloseableUtility.CloseableUtility;
public class Usage {
public static void main(String[] args) {
new Usage();
}
public Usage() {
final ByteArrayInputStream is1 = new ByteArrayInputStream(new byte[]{});
final ByteArrayInputStream is2 = new ByteArrayInputStream(new byte[]{});
final ByteArrayOutputStream os1 = new ByteArrayOutputStream();
final ByteArrayOutputStream os2 = new ByteArrayOutputStream();
try {
new CloseableUtility(is1, is2, os1, os2){
@Override
public void main() throws IOException {
//ex.
//is1.read();
//is2.read();
//os1.write(new byte[]{});
//os2.write(new byte[]{});
}
};
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment