Я пытаюсь понять, как новый пример try-with-resources работает, воссоздавая его, используя регулярные утверждения try-catch-finally. Учитывая следующий тестовый класс с использованием Java 7 try-with-resources:
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class TryWithResources {
public static void main(String[] args) {
try (GZIPOutputStream gzip = new GZIPOutputStream(System.out)) {
gzip.write("TEST".getBytes("UTF-8"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Как бы вы переписали этот класс, чтобы использовать инструкции try-catch-finally, которые производят точно такой же байт-код, что и оператор try-with-resources? Кроме того, тот же вопрос, когда используются два ресурса, как в следующем примере:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class TryWithResources2 {
public static void main(String[] args) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(baos)) {
gzip.write("TEST".getBytes("UTF-8"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}