try-with-resources

Java using scanner with try-with-resources

孤街浪徒 提交于 2019-12-06 01:12:39
I have two versions of Java code that gets user input until user types "q" Version 1: public class Test { public static void main(String[] args) { String input = ""; while (!input.equals("q")) { Scanner scanner = new Scanner(System.in); System.out.print("Input: "); input = scanner.nextLine(); System.out.println("Input was: " + input); } } } Version 2: public class Test { public static void main(String[] args) { String input = ""; while (!input.equals("q")) { try(Scanner scanner = new Scanner(System.in)){ System.out.print("Input: "); input = scanner.nextLine(); System.out.println("Input was: "

Strange “Resource leak: stream is never closed” with try-with-resources if Exception is thrown in a loop

半城伤御伤魂 提交于 2019-12-05 12:03:13
问题 Why is Eclipse giving a strange "Resource leak: zin is never closed" warning for the following code even though I use 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(); } If I modify "anything" on the code, the warning goes away. Below I list 3 modified versions which

Why not using a try with lock in java?

一笑奈何 提交于 2019-12-05 10:28:44
I've read this topic , and this blog article about try with resources locks, as the question popped in my head. But actually, what I'd rather like would be a try with lock , I mean without lock instantiation. It would release us from the verbose lock.lock(); try { //Do some synchronized actions throwing Exception } finally { //unlock even if Exception is thrown lock.unlock(); } Would rather look like : ? implements Unlockable lock ; ... try(lock) //implicitly calls lock.lock() { //Do some synchronized actions throwing Exception } //implicitly calls finally{lock.unlock();} So it would not be a

在 JDK 9 中更简洁使用 try-with-resources 语句

我与影子孤独终老i 提交于 2019-12-05 08:04:54
原本同步至 http://www.waylau.com/concise-try-with-resources-jdk9/ 本文详细介绍了自 JDK 7 引入的 try-with-resources 语句的原理和用法,以及介绍了 JDK 9 对 try-with-resources 的改进,使得用户可以更加方便、简洁的使用 try-with-resources 语句。 在 JDK 7 之前,资源需要手动关闭。 例如下面一个很常见的文件操作的例子: Charset charset = Charset.forName("US-ASCII"); String s = ...; BufferedWriter writer = null; try { writer = Files.newBufferedWriter(file, charset); writer.write(s, 0, s.length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); } finally { if (writer != null) writer.close(); } 在 JDK 7 之前,你一定要牢记在 finally 中执行 close 以释放资源 JDK 7 中的 try-with-resources 介绍

try-with-resources are not supported at this language level - Android

感情迁移 提交于 2019-12-04 15:36:02
问题 I have a problem with "try-with-resources are not supported at this language level" in android in the following posted code, I tried to set language to 7 but it stills keeps giving me the same example plus it keeps giving me the option to change to language 7. public String ReadFile(String fileName) { try (BufferedReader br = new BufferedReader(new FileReader(fileName+".txt"))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb

Is there a cleaner way to use try-with-resource and PreparedStatement?

本小妞迷上赌 提交于 2019-12-04 12:00:05
问题 Here is the Main.java : package foo.sandbox.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Main { public static void main(String[] args) { final String SQL = "select * from NVPAIR where name=?"; try ( Connection connection = DatabaseManager.getConnection(); PreparedStatement stmt = connection.prepareStatement(SQL); DatabaseManager.PreparedStatementSetter<PreparedStatement> ignored = new DatabaseManager

使用try-with-resources替代try finally释放资源

风流意气都作罢 提交于 2019-12-04 08:00:43
1、旧社会 Java里,对于文件操作IO流、数据库连接等开销非常昂贵的资源,用完之后必须及时通过close方法将其关闭,否则资源会一直处于打开状态,直至程序停止,增加系统负担。 关闭资源的常用方式就是在finally块里是释放,即调用close方法。比如,我们经常会写这样的代码: public static void main(String[] args) { BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader("d:\\testing.txt")); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { // handle exception } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { // handle exception } } } 可以看出,为了关闭资源以及处理关闭资源时可能出现的异常,不得不写一大推代码。 2、新时代 2.1 使用新写法 从Java 7开始,jdk提供了一种更好的方式关闭资源,使用try-with

how to use two scanners on one method

非 Y 不嫁゛ 提交于 2019-12-04 06:17:38
问题 earlier today I asked how to re-try/catch input mismatch exception without getting caught by infinite loop but it's two procedures process, at first the game will ask the user for the size of the grid and later after the launch it will ask him either to set up a flag or step over a cell(if mine the game will be over else it will print out the number of surrounding mines), but I get some weird errors the code: int gridSize = 0; try (Scanner scanner = new Scanner(System.in)) { System.out

java try-with-resource not working with scala

≯℡__Kan透↙ 提交于 2019-12-04 02:59:26
In Scala application, am trying to read lines from a file using java nio try-with-resource construct. Scala version 2.11.8 Java version 1.8 try(Stream<String> stream = Files.lines(Paths.get("somefile.txt"))){ stream.forEach(System.out::println); // will do business process here }catch (IOException e) { e.printStackTrace(); // will handle failure case here } But the compiler throws error like ◾not found: value stream ◾A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled. Not sure what is the problem. Am new to using Java NIO, so any help is

Strange “Resource leak: stream is never closed” with try-with-resources if Exception is thrown in a loop

天大地大妈咪最大 提交于 2019-12-03 23:33:50
Why is Eclipse giving a strange "Resource leak: zin is never closed" warning for the following code even though I use 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(); } If I modify "anything" on the code, the warning goes away. Below I list 3 modified versions which are all OK (no warnings). Mod #1: If I remove the for loop from the try block, the warning goes away: /