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

时间:2016-05-31 00:14:58

标签: java android try-catch bufferedreader

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

package milktea.sinker;

import milktea.Sinker;

public class Pearl implements Sinker {

    private Double price;

    public Pearl(Double price){
        this.price = price;
    }

    public Pearl() {      
    }

    @Override
    public String getName() {
        return "Pearl";
    }

    @Override
    public Double getPrice() {
        return this.price;
    }
}

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

1 个答案:

答案 0 :(得分:3)

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

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

相关问题