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



我正在尝试将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循环中收到错误"无法解析符号'缓冲区'"。如何在try函数之外引用BufferReader?我尝试使用"null"初始化 try 块外部的缓冲区读取器,但这导致我的应用程序崩溃。有什么建议吗?

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

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变量。

最新更新