2011-12-19 76 views
1

如何在文本視圖中將文件讀取爲文本文件中的正確顯示? 我可以將文件讀入textview。 但顯示在文本文件中。 我原來的文本文件:如何在文本視圖中將文件讀取爲文本文件中的正確顯示?

Testing this 1 

Satheeshisdf sdf asdfsdfasd fasdfsdfsd 
i can able to do it. 

Trying it       thats all.` 

但是顯示是這樣的:

i can able to do it. 

Trying it       thats all.` 

佈局:

<ScrollView 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:fillViewport="true" 
android:layout_weight="1.0"> 
<TextView 
    android:id="@+id/subtitletv" 
    android:textSize="18dp" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
/> 

計劃:

subtitletv = (TextView)findViewById("R.id.t"); 
try { 
     FileReader fr=new FileReader(selectedfile); 
     BufferedReader br=new BufferedReader(fr); 
     String line = null; 
     try { 
      while(br.readLine()!=null) 
      { 
       line =br.readLine(); 
       subtitletv.append(line); 
       subtitletv.append("\n"); 
      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

UPDATE1: 但現在我無法讀取大文件(50KB)。 小文件加載好。

回答

4

你只是追加每隔一行,因爲你每次讀兩行...

while(br.readLine()!=null) // THIS READS FIRST LINE THEN THIRD LINE 
{ 
    line = br.readLine(); // THIS READS SECOND LINE THEN FOURTH AND SO ON 
    subtitletv.append(line); 
    subtitletv.append("\n"); 
} 

使用...

while((line = br.readLine()) != null) 
{ 
    subtitletv.append(line); 
    subtitletv.append("\n"); 
} 
2

您正在從br每次循環迭代讀取一行。只讀一次。另外,請確保關閉FileReaderfinally區塊。例如:

subtitletv = (TextView)findViewById("R.id.t"); 
FileReader fr = null; 
try { 
    fr = new FileReader(selectedfile); 
    BufferedReader br = new BufferedReader(fr); 
    String line = br.readLine(); 
    while (null != line) { 
     subtitletv.append(line); 
     subtitletv.append("\n"); 
     line = br.readLine(); 
    } 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} finally { 
    if (null != fr) { 
     try { 
      fr.close(); 
     } catch (IOException e) { 
      // ignore 
     } 
    } 
} 
+0

感謝的人。它正在工作。但現在我無法讀取大文件(30KB)。該怎麼辦。 – 2011-12-20 00:11:07

+0

什麼是錯誤? – 2011-12-20 00:20:18

+0

活動未響應。用兩個按鈕等待並確定 – 2011-12-20 00:23:07

相關問題