Java 如何在try/catch块外部引用BufferReader变量
我正在尝试将res/raw/中的csv文件读入SQLite数据库。以下是我的功能: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
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
语句
请注意,这也解决了输入流上的资源泄漏问题,并且不需要初始化
行
变量。是有意义的。我来换一下,试试看。谢谢你的建议!