如何使用Java 6解决CSVReader的尝试资源错误

bey*_*yyy 1 java java-6 opencsv try-with-resources

我被迫用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;        
}
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 5

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();
    }
}
Run Code Online (Sandbox Code Playgroud)