try-with-resources语句
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
public static void writeToFileZipFileContents(String zipFileName,
String outputFileName)
throws java.io.IOException { java.nio.charset.Charset charset =
java.nio.charset.StandardCharsets.US_ASCII;
java.nio.file.Path outputFilePath =
java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with
// try-with-resources statement try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
}
public static void viewTable(Connection con) throws SQLException { String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query); while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " +
price + ", " + sales + ", " + total);
}
} catch (SQLException e) {
JDBCTutorialUtilities.printSQLException(e);
}
}
这是我自己写的:
/**
* 使用try-with-resources块改进异常处理代码
*/
public static void testExecuteQueryNew() {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
// LOGGER.error("can not find driver class",e);
return;
}
try (Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
PreparedStatement preparedStatement = connection.prepareStatement(SQL);
ResultSet resultSet = preparedStatement.executeQuery();
)
{ if (resultSet.next()) {
System.out.println(resultSet.getObject(1)+" : "+resultSet.getObject(2));
}
} catch (Exception e) {
e.printStackTrace();
}
}
AutoCloseable
和 Closeable
接口的javadoc,看看实现了它们的类都有哪些。Closeable接口继承了AutoCloseable接口。不同之处在于,Closeable接口的close方法抛出的是IOException异常,AutoCloseable接口的close方法抛出的是Exception异常。 因此,AutoCloseable的子类可以重写close方法的行为,抛出指定的异常,比如IOException异常,甚至可以不抛出异常。try-with-resources语句的更多相关文章
- Java 复习整理day08
package com.it.demo02_lambda; //接口, 表示动物. //public abstract class Animal { //报错, Lambda表达式只针对于接口有效 p ...
- Java 基础加强 02
基础加强·反射 和 枚举 类的加载概述和加载时机 * A:类的加载概述 * 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载.连接.初始化来实现对这个类的初始化 * 加载 * 就是指 ...
- python第六天 函数 python标准库实例大全
今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...
- whdxlib
1 数据库系统实现 实 验 指 导 书 齐心 彭彬 计算机工程与软件实验中心 2016 年 3 月2目 录实验一.JDBC 应用程序设计(2 学时) ......................... ...
- SQL Server捕获发生The query processor ran out of internal resources and could not produce a query plan...错误的SQL语句
最近收到一SQL Server数据库服务器的告警邮件,告警内容具体如下所示: DATE/TIME: 10/23/2018 4:30:26 PM DESCRIPTION: The query proc ...
- [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...
- MyBatis源码分析-SQL语句执行的完整流程
MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...
- Oracle常用语句集合
oracle常用经典SQL查询 常用SQL查询: .查看表空间的名称及大小 )),) ts_size from dba_tablespaces t, dba_data_files d where t. ...
- phpcmsv9自定义sql语句查询模型实现
在phpcmsv9中,自定义sql语句查询可不太好实现,传入sql语句查询很容易被内部转入生成一系列莫名其妙的sql语句,比如最佳前缀等等,直接造成sql语句查询错误,在此也提供两种解决办法,1修改底 ...
- iOS -Swift 3.0 -for(循环语句用法)
// // ViewController.swift // Swift-循环语句 // // Created by luorende on 16/12/08. // Copyright © 2016年 ...
随机推荐
- HTTPS相关知识以及在golang中的应用
最近简单学习了HTTPS,并在golang中实践了一下,现在把学到的知识记录下来,方便以后查看,如果有幸能帮到有需要的人就更好了,如果有错误欢迎留言指出. 一些简单的概念,可以自行百度百科 HTTPS ...
- (数据科学学习手札38)ggplot2基本图形简述
一.简介 上一篇中我们介绍了ggplot2的基本语法规则,为了生成各种复杂的叠加图层,需要了解ggplot2中一些基本的几何图形的构造规则,本文便就常见的基础几何图形进行说明: 二.各基础图形 2.1 ...
- BZOJ:2763-[JLOI2011]飞行路线(最短路分层图)
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2763 解题心得: 第一次见到分层最短路.其实题中说选择k条路径免费,那怎么选k条路径并没 ...
- 成都Uber优步司机奖励政策(1月7日)
1月7日 奖励政策 滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblog ...
- 3551: [ONTAK2010]Peaks加强版
3551: [ONTAK2010]Peaks加强版 https://www.lydsy.com/JudgeOnline/problem.php?id=3551 分析: kruskal重构树 + 倍增 ...
- GitHub 配置指南
Git和GitHub的区别 GitHub术语解析 配置使用 注册GitHub帐号 创建Git 创建库 复制库 社交化 Git和GitHub的区别 Git是一个分布式的版本控制系统,与SVN类似:最初由 ...
- 14、Java并发编程:CountDownLatch、CyclicBarrier和Semaphore
Java并发编程:CountDownLatch.CyclicBarrier和Semaphore 在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch ...
- Spring Cloud 熔断机制 -- 断路器
Spring Cloud 入门教程(七): 熔断机制 -- 断路器 对断路器模式不太清楚的话,可以参看另一篇博文:断路器(Curcuit Breaker)模式,下面直接介绍Spring Cloud的断 ...
- Spring Boot中使用缓存
Spring Boot中使用缓存 随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一. 原始的使 ...
- android学习五 Intent
1.Intent是组件间调用的桥梁. 2.Android系统定义了很多Intent http://developer.android.com/guide/components/intents-c ...