2016-05-31 86 views
-1

我正嘗試將res/raw /中的csv文件讀入SQLite數據庫。這是我的功能:如何在try/catch塊之外引用一個BufferReader變量

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塊外部的緩衝區讀取器,但這導致我的應用程序崩潰。有什麼建議麼?

回答

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

+0

有道理。我會改變它,並給它一個鏡頭。感謝您的建議! – NBC

+0

它的工作,感謝您的幫助! – NBC

相關問題