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年 ...
随机推荐
- MooseFS及其高可用部署
MooseFS的工作原理分析 MooseFS(下面统一称为MFS)由波兰公司Gemius SA于2008年5月30日正式推出的一款Linux下的开源存储系统,是OpenStack开源云计算项目的子项目 ...
- ARP级ping命令:arping
一.工作原理 地址解析协议,即ARP(Address Resolution Protocol),是根据IP地址获取物理地址的一个TCP/IP协议,是网络链路层的协议,在局域网中使用.主机发送信息时将包 ...
- wireshark抓包分析——TCP/IP协议
本文来自网易云社区 当我们需要跟踪网络有关的信息时,经常会说"抓包".这里抓包究竟是什么?抓到的包又能分析出什么?在本文中以TCP/IP协议为例,简单介绍TCP/IP协议以及如何通 ...
- Xpath语法&示例
一.选取节点常用的路径表达式: 表达式 描述 实例 nodename 选取nodename节点的所有子节点 xpath(‘//div’) 选取了div节点的所有子节点 / 从根节点选取 xpath ...
- WEB网站测试心得整理
一.输入框: 1.正常的字母/文字/数字(正常流程的测试): 2.重复提交(输入内容后,重复点击提交按钮): 3.纯异常字符/正常输入夹杂异常字符(!@#¥%……&**等等): 4.长度限制( ...
- Spring全局变量
压测spring框架的webservice接口,大并发量下响应值与预期值不一致 经查,开发在类中使用全局变量导致: springmvc核心控制器DispatcherServlet 默认为每个contr ...
- Nginx与Ribbon的区别
服务器端负载均衡 Nginx Nginx 基于C语言,快速,性能高5w/s. Redis 5w/s,RibbatMQ 1.2w/s ApacheActiveMQ 0.6w/s 业务系统,kafka 2 ...
- 逆波兰表达式[栈 C 语言 实现]
逆波兰表达式 逆波兰表达式又叫做后缀表达式.在通常的表达式中,二元运算符总是置于与之相关的两个运算对象之间,这种表示法也称为中缀表示.波兰逻辑学家J.Lukasiewicz于1929年提出了另一种表示 ...
- 【shell 练习1】编写Shell条件句练习
实例一.比较两个整数大小 #!/bin/bash while true do read -p "Please input two int nums:" a b >/dev/& ...
- 2018(容斥定理 HDU6286)
2018 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...