Skip to content

Instantly share code, notes, and snippets.

@Kanasansoft
Created February 24, 2012 16:13
Show Gist options
  • Save Kanasansoft/1901819 to your computer and use it in GitHub Desktop.
Save Kanasansoft/1901819 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 class CloseableUtility {
static public void closeAll(Closeable... closeables) throws IOException {
closeAll(Arrays.asList(closeables));
}
private static 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するためのアイディア その1

概要

closeのみを担当するユーティリティメソッド

欠点

  • closeのみの対応で、openは関与しない片手落ち状態がオブジェクト指向に反する気がする
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() {
ByteArrayInputStream is1 = null;
ByteArrayInputStream is2 = null;
ByteArrayOutputStream os1 = null;
ByteArrayOutputStream os2 = null;
try {
is1 = new ByteArrayInputStream(new byte[]{});
is2 = new ByteArrayInputStream(new byte[]{});
os1 = new ByteArrayOutputStream();
os2 = new ByteArrayOutputStream();
//omit
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
CloseableUtility.closeAll(is1, is2, os1, os2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment