如何使用 Java 6 解决 CSVReader 的 try-with-resources 错误

How to solve try-with-resources error for CSVReader using Java 6

我被迫使用 JDK 6 构建 JAR 文件,因为它将在公司笔记本电脑上使用,而笔记本电脑所有者无法在笔记本电脑通过 IT 人员的情况下更新其 Java 版本.

那么,如何解决此方法的 try-with-resources 错误:

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 语法仅在 Java 7 中引入。如果你被迫使用 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();
    }
}