2013-06-04 71 views
0

我有一個基於FileInputStream的函數,該函數應返回從文件中讀取的字符串。但爲什麼返回值是空的。 函數的返回值應該顯示在MainActivity中。 此功能是我的應用程序中的服務的一部分。如何在Android中返回FileInputStream的值

public static String UserLoginFile; 
public static String UserPassFile; 

    public String LoadUserInfopassFromFilePostData() { 
    String FILENAME = "TeleportSAASPass.txt"; 
    FileInputStream inputStream = null; 
    if(UserLoginFile != null){ 
    try { 
     inputStream = openFileInput(FILENAME); 
     byte[] reader = new byte[inputStream.available()]; 
     while (inputStream.read(reader) != -1) {} 
     UserPassFile = new String(reader); 
// Toast.makeText(getApplicationContext(), "GPSTracker " + UserPassFile, Toast.LENGTH_LONG).show(); 
    } catch(IOException e) { 
    } finally { 
     if (inputStream != null) { 
      try { 
       inputStream.close(); 
      } catch (IOException e) { 
      } 
     } 
    } 
    } 
    return UserPassFile; 
} 

請告訴我如何解決我的功能,以便它可以返回她從文件中讀取的字符串。

+0

你是否確信你沒有捕捉任何異常?您也可以嘗試DataInputStream並執行readLine() – britzl

回答

1

考慮您的代碼之間的區別:

 while (inputStream.read(reader) != -1) {} 
     UserPassFile = new String(reader); 

這種另類和:

 while (inputStream.read(reader) != -1) { 
      UserPassFile = new String(reader); 
     } 

在你的情況,UserPassFile從讀者每閱讀()調用之後分配,包括最後其中一個失敗。在第二種情況下,僅在讀取成功後才分配UserPassFile,因此在到達方法結束時仍應包含一個非空字符串以返回。

但是,你似乎在做另外一件奇怪的事情。你假設你將能夠在一次讀取中讀取整個.available()數據量,這可能是真的(至少如果你能夠分配一個大的byte [])。然而,在閱讀這些數據後,你再試一次,看看你是否失敗了,這似乎是不必要的。看起來,如果你打算假設你可以一次性讀取數據,那麼你應該簡單地關閉流並返回,一旦你這樣做 - 似乎沒有一個令人信服的理由嘗試又一次閱讀,預計會失敗。否則,如果有可能無法在單個讀取中獲取所有數據(),則應記錄您已獲得的數量並繼續追加,直到讀取失敗或以其他方式確定完成爲止。

1

我會建議使用輸入流閱讀器。退房 http://developer.android.com/reference/java/io/InputStreamReader.html 您的代碼看起來類似:

inputStream = openFileInput(FILENAME); 
InputStreamReader(inputstream, "UTF_8"), 8); 
StringBuilder response = new StringBuilder(); 
String line; 
//Read the response from input stream line-wise 

while((line = reader.readLine()) != null){ 
response.append(line).append('\n'); 
} 

//Create response string 
result = response.toString(); 
//Close input stream 
reader.close();