如何使用Java 6解决CSVReader的资源试用错误
我被迫用JDK 6构建JAR文件,因为它将在公司的笔记本电脑上使用,笔记本电脑所有者无法在笔记本电脑没有经过it人员检查的情况下更新其Java版本 因此,如何解决此方法的“尝试使用资源”错误:如何使用Java 6解决CSVReader的资源试用错误,java,java-6,opencsv,try-with-resources,Java,Java 6,Opencsv,Try With Resources,我被迫用JDK 6构建JAR文件,因为它将在公司的笔记本电脑上使用,笔记本电脑所有者无法在笔记本电脑没有经过it人员检查的情况下更新其Java版本 因此,如何解决此方法的“尝试使用资源”错误: public static String importFile(String filepath){ String insertQuery = "INSERT INTO SALESMAN VALUES (?,?)"; String status; try (CSVReader re
public static String importFile(String filepath){
String insertQuery = "INSERT INTO SALESMAN VALUES (?,?)";
String status;
try (CSVReader reader = new CSVReader(new FileReader(filepath), ','); //error here
Connection connection = DBConnection.getConnection();){
Statement stmt = connection.createStatement();
PreparedStatement pstmt = connection.prepareStatement(insertQuery);
String[] rowData = null;
int i = 0;
while((rowData = reader.readNext()) != null){
for (String data : rowData){
pstmt.setString((i % 2) + 1, data);
if (++i % 2 == 0)
pstmt.addBatch();
if (i % 20 == 0)
pstmt.executeBatch();
}
}
status = "Successfully uploaded";
} catch (Exception ex) {
ex.printStackTrace();
}
return status;
}
try-with-resource语法仅在Java7中引入。如果您被迫使用Java 6,您必须求助于一个好的老式
finally
子句:
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filepath), ',');
// Code from the original try block, removed for brevity's sake
} catch (Exception ex) {
ex.printStackTrace(); // Or some useful error handling
} finally { // closing the reader in the finally block
if (reader != null) {
reader.close();
}
}
try-with-resource语法仅在Java7中引入。如果您被迫使用Java 6,您必须求助于一个好的老式
finally
子句:
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filepath), ',');
// Code from the original try block, removed for brevity's sake
} catch (Exception ex) {
ex.printStackTrace(); // Or some useful error handling
} finally { // closing the reader in the finally block
if (reader != null) {
reader.close();
}
}
“CSVReader”构造函数抛出异常时的情况如何?这就给你留下了一个未关闭的“FileReader”对象…@Grogi这也没有在OP中处理,所以我没有解决它。一般来说,您应该在
try
块外声明所有资源引用变量,在块内初始化它们,然后在finally
块中关闭它们,顺序与初始化顺序相反。“CSVReader”构造函数引发异常时的情况如何?这就给你留下了一个未关闭的“FileReader”对象…@Grogi这也没有在OP中处理,所以我没有解决它。一般来说,您应该在try
块外声明所有资源引用变量,在块内初始化它们,然后在finally
块中关闭它们,顺序与初始化顺序相反。