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年 ...
随机推荐
- 通过burpsuite替换cookie登录后台
通过burpsuite可以比较方便的替换http头部的cookie.useragent等字段,在获取到用户的cookie后实现登录.具体使用方法如下: 如替换cookie,可以写正则表达式^Cooki ...
- 006---Linux用户、群组和权限
用户.组.权限管理 用户管理 增 语法:useradd -c '添加用户1' user1 选项和参数: -c:用户的备注信息 -d:用户的家目录 -g:指定用户所属的用户组(gid) -s:指定用户登 ...
- .Net 面试题 汇总(五)
1.简述javascript中的“=.==.===”的区别? =赋值 ==比较是否一般相等 "3"==3 //会做类型的隐式转换,true ===比较是否严格相等 "3& ...
- Java String源码解析
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { ...
- underscore.js 分析 第一天
Underscore 是一个非常实用的Javascript类库. 通过研究他能提高自身的JS水平. 我们看到整个代码被 (function() { /* 代码 */ }.call(this)); 包 ...
- Fat Jar - Myeclipse插件安装使用方法- 完美解决
Eclipse可以安装一个叫Fat Jar的插件,用这个插件打包非常方便,Fat Jar的功能非常强大. 工具/原料 Eclipse Kepler Fat Jar 方法/步骤 1 Fat Jar功能非 ...
- datawindow自动换行打印,需结合该函数一起使用
1.设置 具体步骤如下: 1) 在DataWindow Painter中打开此DataWindow对象. 2) 在需设定自动折行的列上双击鼠标, 弹开此列的属性窗口. 3) 选择P ...
- 获取App的PackageName包名和LauncherActivity启动页
第一种情况: 查看手机里面已经安装的App: 用数据线连接手机, 打开开发者模式, 并赋予相关权限: 1. 清除日志: adb logcat -c 2. 启动日志: adb logcat Activi ...
- lesson 15 Fifty pence worth of trouble
lesson 15 Fifty pence worth of trouble appreciate =be grateful for We really appreciate all the help ...
- Siki_Unity_2-1_API常用方法和类详细讲解(下)
Unity 2-1 API常用方法和类详细讲解(下) 任务101&102:射线检测 射线origin + direction:射线检测:射线是否碰撞到物体 (物体需要有碰撞器),碰撞物体的信息 ...