Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在try/catch块外部引用BufferReader变量_Java_Android_Try Catch_Bufferedreader - Fatal编程技术网

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

Java 如何在try/catch块外部引用BufferReader变量,java,android,try-catch,bufferedreader,Java,Android,Try Catch,Bufferedreader,我正在尝试将res/raw/中的csv文件读入SQLite数据库。以下是我的功能: public void updateDatabase(Context context, SQLiteDatabase database) { InputStream inputStream = context.getResources().openRawResource(R.raw.teamlist); try { BufferedReader buffer = new Buff

我正在尝试将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循环中得到错误“无法解析符号‘buffer’”。如何在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
语句


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

是有意义的。我来换一下,试试看。谢谢你的建议!