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

问题描述 投票:1回答:1

我被迫用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;        
}
java java-6 opencsv try-with-resources
1个回答
4
投票

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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.