2011-08-24 184 views
18

我有一個文件包含單獨的文本行。
我想先顯示行,然後如果我按下按鈕,第二行應該顯示在TextView中,第一行應該消失。然後,如果再次按下,則應顯示第三行,依此類推。如何獲取文件逐行閱讀

我是否必須使用TextSwitcher或其他? 我該怎麼做?

回答

31

你標記爲「Android的資產,」所以我會假設你的文件是在資產的文件夾。這裏:

InputStream in; 
BufferedReader reader; 
String line; 
TextView text; 

public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    text = (TextView) findViewById(R.id.textView1); 
    in = this.getAssets().open(<your file>); 
    reader = new BufferedReader(new InputStreamReader(in)); 
    line = reader.readLine(); 

    text.setText(line); 
    Button next = (Button) findViewById(R.id.button1); 
    next.setOnClickListener(this); 
} 

public void onClick(View v){ 
    line = reader.readLine(); 
    if (line != null){ 
     text.setText(line); 
    } else { 
     //you may want to close the file now since there's nothing more to be done here. 
    } 
} 

試試這個。我無法確認它是否完全正常工作,但我相信這是您想遵循的一般想法。當然,你會想用你在佈局文件中指定的名稱替換任何R.id.textView1/button1

另外:爲了空間的緣故,這裏檢查的錯誤非常少。您需要檢查您的資產是否存在,並且我確信在打開文件供閱讀時應該有一個try/catch區塊。

編輯︰大錯誤,這不是R.layout,這是R.id我已編輯我的答案來解決問題。

+1

你也可以通過接受一個答案來獲得聲望,如果它對你有幫助。 – Otra

15

下面的代碼應滿足您的需要

try { 
// open the file for reading 
InputStream instream = new FileInputStream("myfilename.txt"); 

// if file the available for reading 
if (instream != null) { 
    // prepare the file for reading 
    InputStreamReader inputreader = new InputStreamReader(instream); 
    BufferedReader buffreader = new BufferedReader(inputreader); 

    String line; 

    // read every line of the file into the line-variable, on line at the time 
    do { 
    line = buffreader.readLine(); 
    // do something with the line 
    } while (line != null); 

} 
} catch (Exception ex) { 
    // print stack trace. 
} finally { 
// close the file. 
instream.close(); 
} 
+0

你從哪裏得到'openFileInput()' - 方法?另外,你應該總是使用「try/finally」塊來關閉流(所以當異常拋出時它們會關閉)。 –

+1

正確的方法,但是你使用了C風格的條件,它不會編譯。 '不允許自動從空/整型/賦值等轉換爲布爾型,所以'if(instream)'和'while(line = buffreader.readLine())'需要替換爲'if(instream!= null )'和'while(buffreader.hasNext())' –

+1

BufferedReader沒有hasNext()函數,只是檢查它是否爲空 –

0

您只需使用一個TextView和ButtonView。使用BufferedReader讀取文件,它將爲您提供一個很好的API來逐一讀取行。點擊按鈕,通過使用settext來改變文本視圖的文本。

您也可以考慮閱讀所有文件內容並將其放入字符串列表中,如果您的文件不太大,則可以更清晰。

問候, 斯特凡