ARM自动资源管理 try(){}

本文介绍了Java7的自动资源管理(ARM)块特性,通过一个使用Geotools库的示例展示了如何在try-with-resources语句中优雅地管理FeatureWriter资源。无论代码是否抛出异常,资源都会被正确关闭。这个特性依赖于资源实现AutoCloseable接口,如示例中的FeatureWriter。在示例中,数据从一个源转换并写入到shapefile,确保了在处理过程中资源的高效和安全释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ARM自动资源管理 try(){}

在看geotools的示例代码过程中看到了try(…){…}写法

  try (FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
                     dataStore.getFeatureWriterAppend(createdName, transaction);
             SimpleFeatureIterator iterator = featureCollection.features()) {
            while (iterator.hasNext()) {
                // copy the contents of each feature and transform the geometry
                SimpleFeature feature = iterator.next();
                SimpleFeature copy = writer.next();
                copy.setAttributes(feature.getAttributes());

                Geometry geometry = (Geometry) feature.getDefaultGeometry();
                Geometry geometry2 = JTS.transform(geometry, transform);

                copy.setDefaultGeometry(geometry2);
                writer.write();
            }
            transaction.commit();
            JOptionPane.showMessageDialog(null, "Export to shapefile complete");
        } catch (Exception problem) {
            problem.printStackTrace();
            transaction.rollback();
            JOptionPane.showMessageDialog(null, "Export to shapefile failed");
        } finally {
            transaction.close();
        }

从网上查阅资料得知从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

无论代码是否出现异常,()中的资源都会自动关闭。

前提是,这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。

例如上述的FeatureWrite就继承Closeable接口,Closeable接口又继承java.lang.AutoCloseable接口。


public interface FeatureWriter<T extends FeatureType, F extends Feature> extends Closeable {
    T getFeatureType();

    F next() throws IOException;

    void remove() throws IOException;

    void write() throws IOException;

    boolean hasNext() throws IOException;

    void close() throws IOException;
}

public interface Closeable extends AutoCloseable {

    /**
     * Closes this stream and releases any system resources associated
     * with it. If the stream is already closed then invoking this
     * method has no effect.
     *
     * <p> As noted in {@link AutoCloseable#close()}, cases where the
     * close may fail require careful attention. It is strongly advised
     * to relinquish the underlying resources and to internally
     * <em>mark</em> the {@code Closeable} as closed, prior to throwing
     * the {@code IOException}.
     *
     * @throws IOException if an I/O error occurs
     */
    public void close() throws IOException;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值