Skip to content

Instantly share code, notes, and snippets.

@Kanasansoft
Created February 24, 2012 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kanasansoft/1902455 to your computer and use it in GitHub Desktop.
Save Kanasansoft/1902455 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(closeables);
closeAll(closeables);
}
abstract public void main(Closeable... closeables) 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するためのアイディア その2

概要

インスタンス化時に渡されたストリームが、mainメソッドに渡される (Rubyのイテレータに近い)

欠点

  • キャストがキモい
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import com.kanasansoft.CloseableUtility.CloseableUtility;
public class Usage {
public static void main(String[] args) {
new Usage();
}
public Usage() {
ByteArrayInputStream is1 = new ByteArrayInputStream(new byte[]{});
ByteArrayInputStream is2 = new ByteArrayInputStream(new byte[]{});
ByteArrayOutputStream os1 = new ByteArrayOutputStream();
ByteArrayOutputStream os2 = new ByteArrayOutputStream();
try {
new CloseableUtility(is1, is2, os1, os2){
@Override
public void main(Closeable... closeables) throws IOException {
ByteArrayInputStream is1 = (ByteArrayInputStream) closeables[0];
ByteArrayInputStream is2 = (ByteArrayInputStream) closeables[1];
ByteArrayOutputStream os1 = (ByteArrayOutputStream) closeables[2];
ByteArrayOutputStream os2 = (ByteArrayOutputStream) closeables[3];
//ex.
//is1.read();
//is2.read();
//os1.write(new byte[]{});
//os2.write(new byte[]{});
//omit
}
};
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment