2016-04-29 73 views
1

最近如何處理FileNotFoundException?

我試着A.txt文件讀取內容。

,但如果我的設備沒有A.TXT,發生FileNotFoundException異常

,所以我想,如果我的設備沒有a.txt中,我怎麼能留下來繼續?

String path = "/sdcard/Download"; 
    String textName = "a.txt"; 

    String serverVersion = null; 
    BufferedReader br = null; 
    try { 
     br = BufferedReaderFactory.create(path, textName); 

     StringBuilder contentGetter = new StringBuilder(); 
     while ((serverVersion = br.readLine()) != null) { 

      serverVersion = serverVersion.trim().toLowerCase(); 
      contentGetter.append('\n' + serverVersion); 
      Log.d(TAG, " myServerVersion = " + serverVersion); 
      break; 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

回答

0

看起來你已經在處理異常了。如果沒有文件,你的代碼將按計劃繼續。在你的try/catch塊之後,你應該檢查if(serverVersion == null),如果它返回true,你就知道serverVersion沒有從文件中讀取。

+0

我試着去'否則,如果(serverVersion! = indeviceVersion || serverVersion.equals(null))'add compareVersion part。但是..在這裏相同 –

+0

啊,現在你有一個NullPointerException,因爲你試圖在空值上使用'.equals()' update: 試試這個'else if(serverVersion == null ||!serverVersion.equals (indeviceVersion))' 請注意我在*'serverVersion == null'之後如何使用'serverVersion.equals()'*。這不會返回空指針異常,因爲如果'serverVersion == null',則忽略if語句的其餘部分。 –

+0

對不起?我嘗試'else if(serverVersion == null ||!serverVersion.equals(indeviceVersi)){但同樣的例外。 ..對不起 –

1

您可以簡單的創建一個像

boolean isFileFound = false; 

所以try/catch語句前一個變量,在最後的嘗試設置isFileFound = true 像:

String path = "/sdcard/Download"; 
    String textName = "a.txt"; 

    boolean isFileFound = false; 

    String serverVersion = null; 
    BufferedReader br = null; 
    try { 
     br = BufferedReaderFactory.create(path, textName); 

     StringBuilder contentGetter = new StringBuilder(); 
     while ((serverVersion = br.readLine()) != null) { 

      serverVersion = serverVersion.trim().toLowerCase(); 
      contentGetter.append('\n' + serverVersion); 
      Log.d(TAG, " myServerVersion = " + serverVersion); 
      break; 
     } 
     isFileFound = true; 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    if (!isFileFound){ // This is equals to if(isFileFound != null) 
     //Do some message here, like: 
     Toast toast = Toast.makeText(context, "File not found", Toast.LENGTH_SHORT).show(); 
    } 
+0

謝謝。我有1個問題。如果(isFileFound){內容是什麼? –

+0

我不明白爲什麼要添加isFileFound? –

+0

我已經將條件(if)更改爲if(isFileFound!= null)或if(!isFileFound)。你可以放一些消息,任何東西......或者只是忽略(你不需要if),但如果你不使用任何條件,你不需要變量isFileFound。這個變量只是說「嘿,我執行所有的嘗試內容沒有錯誤」 – Adley