2012-05-18 60 views
0

我已經解決了我自己的問題,但我不知道爲什麼我的第一次嘗試不工作,我希望有人可以告訴我爲什麼。 我也希望如果有人能告訴我,如果我的最終解決方案是一個「好」的或不(這是我的意思,它是有效的)?Android的FileInputStream代碼導致崩潰

這是我在讀我先前已創建的輸入文件的第一次嘗試:

private byte[] mInputData; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.second_view); 

    Intent myIntent = getIntent(); 

    mFilename = myIntent.getStringExtra("FILENAME"); 
    mSplitSeq = myIntent.getStringExtra("SPLIT_SEQ"); 

    try { 
     fis = openFileInput(mFilename); 
     fis.read(mInputData); 
     fis.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

這是我在網上找到的是實際工作:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.second_view); 

    Intent myIntent = getIntent(); 

    mFilename = myIntent.getStringExtra("FILENAME"); 
    mSplitSeq = myIntent.getStringExtra("SPLIT_SEQ"); 

    try { 
     fis = openFileInput(mFilename); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); 
     String line = null, input=""; 
     while ((line = reader.readLine()) != null) 
      mTimeStr += line; 
     reader.close(); 
     fis.close(); 
     //fis.read(mInputData); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

我與我的第一次收到此錯誤當調用fis.read(mInputData)函數時,實現是NullPointerException。

回答

3

我很確定這是因爲mInputData從未初始化。你需要一個像mInputData = new byte[1000];那樣的線路。相反,您告訴read()將數據提供給等於null的引用,即NullPointerException。

+0

啊,這是有道理的。有沒有辦法使字節數組動態? 我想第二個解決方案是動態的,但能夠調用一個讀取全部沒有循環的讀取函數將會很好。 – J2N

+0

你可以使用'int byteArraySize = new File(mFileName).length()'。 File上的長度方法以字節爲單位返回大小。 – MattDavis

+0

謝謝,我喜歡 – J2N