インスタンス化時に渡されたストリームが、mainメソッドに渡される (Rubyのイテレータに近い)
- キャストがキモい
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())); | |
} | |
} | |
} |
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(); | |
} | |
} | |
} |