closeのみを担当するユーティリティメソッド
- closeのみの対応で、openは関与しない片手落ち状態がオブジェクト指向に反する気がする
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())); | |
} | |
} | |
} |
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(); | |
} | |
} | |
} | |
} |