Tag: try with resources

在Java 6中模拟try-with-resources的最佳方法是什么?

事实certificate,几乎没有人正确地关闭Java中的资源。 程序员根本不使用try-finally块,或者只是将resource.close()放在finally中也是不正确的(因为来自close() Throwable可以从try块中影响Throwable )。 有时它们会放置像IOUtils.closeQuietly()这样的东西,它只适用于InputStream ,但不适用于OutputStream 。 try-with-resources解决了所有这些问题,但仍然有大量用Java 6编写的项目。 在Java 6中模拟try-with-resources的最佳方法是什么? 现在我使用Guava Closer ,它比什么都好,但仍然比try-with-resources更丑。 此外,还有一种称为贷款模式的模式,但Java中缺少lambdas使得这种模式非常麻烦。 有没有更好的办法?

为什么不在java中使用带锁的try?

我已经阅读了这个主题 , 这篇关于尝试使用资源锁定的博客文章 ,正如我脑海中浮现的那样。 但实际上,我更喜欢的是带锁的尝试 ,我的意思是没有锁实例化。 它会让我们从冗长中解脱出来 lock.lock(); try { //Do some synchronized actions throwing Exception } finally { //unlock even if Exception is thrown lock.unlock(); } 宁愿看起来像: ? implements Unlockable lock ; … try(lock) //implicitly calls lock.lock() { //Do some synchronized actions throwing Exception } //implicitly calls finally{lock.unlock();} 所以它不是TWR ,而只是一些样板清洁。 您是否有任何技术理由建议描述为什么这不是一个合理的想法? 编辑:澄清我建议和简单的synchronized(lock){}块之间的区别,检查此片段: import java.util.concurrent.locks.Condition; […]

Java隐含try-with-resources

我想知道以下代码是否正确使用了try-with-resources。 try (ResultSet rs = new QueryBuilder(connection, tableName(), getPaths(), searchQuery()).add(constraint).build().executeQuery()) { while (rs.next()) { beans.add(createBean(rs)); } } 争论并不重要,唯一重要的是: new QueryBuilder().build(); 返回PreparedStatement 。 我完全理解rs会被关闭,但PreparedStatement也会被关闭,如果是这样,出于什么原因? 因为ResultSet关闭还是因为try-with-resources?

如果在循环中抛出exception,则使用try-with-resources奇怪的“资源泄漏:流永远不会关闭”

为什么Eclipse给出了一个奇怪的“资源泄漏:zin永远不会关闭”警告以下代码,即使我使用try-with-resources : Path file = Paths.get(“file.zip”); // Resource leak warning! try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) { for (int i = 0; i < 5; i++) if (Math.random() < 0.5) throw new Exception(); } catch (Exception e) { e.printStackTrace(); } 如果我在代码上修改“任何东西”,警告就会消失。 下面我列出了3个修改过的版本都没问题(没有警告)。 Mod#1:如果我从try块中删除for循环,则警告消失: // This is OK (no warning) try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) […]

try-with-resource中的close()exception

我正在阅读JDK7中的try-with-resource,当我考虑升级我的应用程序以使用JDK7运行时,我遇到了这个问题。 当使用BufferedReader时,例如写入抛出IOException和close抛出IOException ..在catch块中我关注写入引发的IOException ..但是我不会太在意关闭抛出的那个.. 数据库连接..和任何其他资源的相同问题.. 作为一个例子,我创建了一个自动关闭资源: public class AutoCloseableExample implements AutoCloseable { public AutoCloseableExample() throws IOException{ throw new IOException(); } @Override public void close() throws IOException { throw new IOException(“An Exception During Close”); } } 现在使用它时: public class AutoCloseTest { public static void main(String[] args) throws Exception { try (AutoCloseableExample example = new AutoCloseableExample()) { […]

为什么ExecutorService接口没有实现AutoCloseable?

未能在线程执行程序上调用shutdown()将导致永不终止的应用程序。 关闭ExecutorService的最佳做法是: ExecutorService service = null; try { service = Executors.newSingleThreadExecutor(); // Add tasks to thread executor … } finally { if(service != null) service.shutdown(); } 由于Java知道try-with-resources概念,如果我们能做到这一点会不会很好? try (service = Executors.newSingleThreadExecutor()) { // Add tasks to thread executor … }

为什么try-with-resources catch块选择性地可选?

我读到try-with-resources中的catch块是可选的。 我尝试在try-with-resources块中创建一个Connection对象,没有后续的catch块,只是为了从eclipse中获取编译器错误:“自动close()调用引发的未处理的exception类型SQLException 。” 由于可以在try-with-resources中使用的每个资源都实现了AutoCloseable ,因此在调用close()方法时可能抛出exception,我不明白catch子句是如何可选的,因为它不允许我跳过从close()捕获exception。 是否有一些特殊要求, AutoCloseable的具体实现不直接声明其close()方法中抛出的任何exception? (例如,重写AutoCloseable的close() throws Exception一个带有close()exception,它不会抛出任何exception)? ..或者这可能只是一个日食问题? 编辑:这是仍然触发问题的最简单的代码片段: try (Connection con = dataSource.getConnection()) { /*…*/ } 关于这是否与使用JNDI数据源有关的想法? 提前致谢。

声纳:如何使用try-with-resources关闭FileOutputStream

声纳正在给出一个错误,即应关闭此FileOutputStream 。 我需要修改以下代码以使用try-with-resources 。 我该怎么做呢? public void archivingTheFile(String zipFile){ byte[] buffer = new byte[1024]; try{ FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); for(String file : this.fileList){ ZipEntry ze= new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); […]

流关闭而不是重新打开 – Java

我有一个简单的’功课’,但我发现输入流的关闭有点问题。 简单来说,我必须用Java创建一个联系人’列表’应用程序,只是以正确的方式使用多态。 所以我有一个类Contact和一个子类Private(联系人)。 在这两个类中都有一个修改方法来更改变量的值。 public void modify() throws IOException { System.out.println(“Previously name: ” + name); System.out.println(“Insert new name”); try(InputStreamReader ir = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(ir) ) { name= in.readLine(); System.out.println(“You’ve changed the name to: “+ name); System.out.println(“Previously surname: ” + surname); System.out.println(“Insert new surname”); surname= in.readLine(); System.out.println(“You’ve changed the surname to: “+ […]

使用try-with-resources时需要flush()调用

try-with-resources隐式调用flush()吗? 如果是,在下面的代码片段中,可以安全地删除bw.flush()吗? static void printToFile1(String text, File file) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(text); bw.flush(); } catch (IOException ex) { // handle ex } } PS。 我在官方文件中没有看到任何关于它的描述: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html https://docs.oracle.com/javase/8/docs/api/java/lang/Au​​toCloseable.html