如何在 try/catch 块之外引用 BufferReader 变量

How to reference a BufferReader variable outside of try/catch block

我正在尝试将 res/raw/ 中的 csv 文件读入 SQLite 数据库。这是我的功能:

public void updateDatabase(Context context, SQLiteDatabase database) {

    InputStream inputStream = context.getResources().openRawResource(R.raw.teamlist);
    try {
        BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    } catch (UnsupportedEncodingException ioe) {
        Log.e("ERROR", "Could not load " + ioe);
    }

    String line = "";

    database.beginTransaction();
    try {
        while ((line = buffer.readLine()) != null) {
            // read each line from CSV file into a database

        }
    } catch (IOException ioe){
        Log.e("ERROR", "Could not load " + ioe);
    }
    database.setTransactionSuccessful();
    database.endTransaction();
}

但是我在 while 循环中得到错误 "Cannot resolve symbol 'buffer'"。如何在 try 函数之外引用 BufferReader?我尝试使用 "null" 在 try 块外初始化缓冲区 reader,但这导致我的应用程序崩溃。有什么建议吗?

不要这样写代码。更正确的写法是:

public void updateDatabase(Context context, SQLiteDatabase database) {

    try (InputStream inputStream = context.getResources().openRawResource(R.raw.teamlist);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));) {

        String line;
        database.beginTransaction();
        while ((line = buffer.readLine()) != null) {
            // read each line from CSV file into a database

        }
        database.setTransactionSuccessful();
        database.endTransaction();
    } catch (IOException ioe){
        Log.e("ERROR", "Could not load " + ioe);
    } catch (UnsupportedEncodingException ioe) {
        Log.e("ERROR", "Could not load " + ioe);
    }
}

总而言之,依赖于先前 try 块中代码成功的代码应该在该 try 块中。不要像你那样写 try/catch 语句的字符串。

请注意,这也解决了输入流上的资源泄漏问题,并且 line 变量不需要初始化。