2010-11-03 110 views
95

事情很簡單,但不應按預期工作。Android閱讀文本原始資源文件

我有一個文本文件作爲原始資源添加。該文本文件包含文本,如:

B)如果適用法律要求提供與對於 軟件的任何擔保,所有此類擔保在 有效期僅限於九十(自交貨之日起90) DAYS 。

(c)中的口頭或書面的信息或 建議都VIRTUAL定向, ITS經銷商,分銷商,代理或 僱員將CREATE以任何方式保證或 提高任何 擔保本文提供的範圍。

(d)(美國只)一些州不 ALLOW暗示 擔保的排除,因此上述排除可能 不適用於您。本保修提供 您具體的法律權利,您可能還有其他法律權利,因爲這些 不同國家之間不同。

在我的屏幕我有一個這樣的佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center" 
        android:layout_weight="1.0" 
        android:layout_below="@+id/logoLayout" 
        android:background="@drawable/list_background"> 

      <ScrollView android:layout_width="fill_parent" 
         android:layout_height="fill_parent"> 

        <TextView android:id="@+id/txtRawResource" 
           android:layout_width="fill_parent" 
           android:layout_height="fill_parent" 
           android:padding="3dip"/> 
      </ScrollView> 

    </LinearLayout> 

讀取原始資源的代碼是:

TextView txtRawResource= (TextView)findViewById(R.id.txtRawResource); 

txtDisclaimer.setText(Utils.readRawTextFile(ctx, R.raw.rawtextsample); 

public static String readRawTextFile(Context ctx, int resId) 
{ 
    InputStream inputStream = ctx.getResources().openRawResource(resId); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

    int i; 
    try { 
     i = inputStream.read(); 
     while (i != -1) 
     { 
      byteArrayOutputStream.write(i); 
      i = inputStream.read(); 
     } 
     inputStream.close(); 
    } catch (IOException e) { 
     return null; 
    } 
    return byteArrayOutputStream.toString(); 
} 

文本得到的顯示,但在每行後,我收到了奇怪的人物[]如何刪除該人物?我認爲這是新線。

工作液

public static String readRawTextFile(Context ctx, int resId) 
{ 
    InputStream inputStream = ctx.getResources().openRawResource(resId); 

    InputStreamReader inputreader = new InputStreamReader(inputStream); 
    BufferedReader buffreader = new BufferedReader(inputreader); 
    String line; 
    StringBuilder text = new StringBuilder(); 

    try { 
     while ((line = buffreader.readLine()) != null) { 
      text.append(line); 
      text.append('\n'); 
     } 
    } catch (IOException e) { 
     return null; 
    } 
    return text.toString(); 
} 

回答

54

如果您使用的是基於字符的BufferedReader,而不是基於字節的InputStream的?

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
String line = reader.readLine(); 
while (line != null) { ... } 

不要忘了readLine()跳過了新行!

140

您可以使用此:

try { 
     Resources res = getResources(); 
     InputStream in_s = res.openRawResource(R.raw.help); 

     byte[] b = new byte[in_s.available()]; 
     in_s.read(b); 
     txtHelp.setText(new String(b)); 
    } catch (Exception e) { 
     // e.printStackTrace(); 
     txtHelp.setText("Error: can't show help."); 
    } 
+4

我不知道該Inputstream.available()這裏是正確的選擇,而讀取n到一個ByteArrayOutputStream直到n ==可-1。 – ThomasRS 2012-04-30 08:32:22

+12

這可能無法適用於大型資源。它取決於輸入流讀取緩衝區的大小,並且只能返回一部分資源。 – d4n3 2012-06-29 06:19:13

+4

@ d4n3是正確的,輸入流可用方法的文檔狀態爲:「返回可讀取或跳過的字節的估計數量,不會阻塞更多的輸入 請注意,此方法提供了這樣一個弱保證,它不是在實踐中非常有用「 – ozba 2013-04-10 14:18:30

2

這是另一種方法,這肯定會工作,但我不能讓它讀取多個文本文件查看多個textviews在一個單一的活動,任何人都可以幫忙嗎?

TextView helloTxt = (TextView)findViewById(R.id.yourTextView); 
    helloTxt.setText(readTxt()); 
} 

private String readTxt(){ 

InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile); 
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

int i; 
try { 
i = inputStream.read(); 
while (i != -1) 
    { 
    byteArrayOutputStream.write(i); 
    i = inputStream.read(); 
    } 
    inputStream.close(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 

return byteArrayOutputStream.toString(); 
} 
1

@borislemke您可以通過類似的方式像

TextView tv ; 
findViewById(R.id.idOfTextView); 
tv.setText(readNewTxt()); 
private String readNewTxt(){ 
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile); 
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

int i; 
try { 
i = inputStream.read(); 
while (i != -1) 
    { 
    byteArrayOutputStream.write(i); 
    i = inputStream.read(); 
    } 
    inputStream.close(); 
    } catch (IOException e) { 
    // TODO Auto-generated catch block 
e.printStackTrace(); 
} 

return byteArrayOutputStream.toString(); 
} 
24

做到這一點。如果你使用Apache的 「公地IO」 IOUtils那就更簡單了:

InputStream is = getResources().openRawResource(R.raw.yourNewTextFile); 
String s = IOUtils.toString(is); 
IOUtils.closeQuietly(is); // don't forget to close your streams 

依賴:http://mvnrepository.com/artifact/commons-io/commons-io

Maven的:

<dependency> 
    <groupId>commons-io</groupId> 
    <artifactId>commons-io</artifactId> 
    <version>2.4</version> 
</dependency> 

搖籃:

'commons-io:commons-io:2.4' 
+0

我應該輸入什麼來使用IOUtils? – 2013-06-08 01:58:23

+1

Apache commons-io庫(http://commons.apache.org/proper/commons-io/)。或者如果你使用Maven(http://mvnrepository.com/artifact/commons-io/commons-io)。 – tbraun 2013-06-10 08:53:38

+6

對於gradle:編譯「commons-io:commons-io:2.1」 – JustinMorris 2014-10-24 20:58:26

3

而是做這種方式:

// reads resources regardless of their size 
public byte[] getResource(int id, Context context) throws IOException { 
    Resources resources = context.getResources(); 
    InputStream is = resources.openRawResource(id); 

    ByteArrayOutputStream bout = new ByteArrayOutputStream(); 

    byte[] readBuffer = new byte[4 * 1024]; 

    try { 
     int read; 
     do { 
      read = is.read(readBuffer, 0, readBuffer.length); 
      if(read == -1) { 
       break; 
      } 
      bout.write(readBuffer, 0, read); 
     } while(true); 

     return bout.toByteArray(); 
    } finally { 
     is.close(); 
    } 
} 

    // reads a string resource 
public String getStringResource(int id, Charset encoding) throws IOException { 
    return new String(getResource(id, getContext()), encoding); 
} 

    // reads an UTF-8 string resource 
public String getStringResource(int id) throws IOException { 
    return new String(getResource(id, getContext()), Charset.forName("UTF-8")); 
} 

活動,加

public byte[] getResource(int id) throws IOException { 
     return getResource(id, this); 
} 

或從測試用例,加

public byte[] getResource(int id) throws IOException { 
     return getResource(id, getContext()); 
} 

,看你的錯誤處理 - 不抓,而忽略異常當你的資源必須存在或某事(很?)錯。

+0

你需要關閉由'openRawResource()'打開的流嗎? – 2013-04-29 08:38:15

+0

我不知道,但那肯定是標準的。更新示例。 – ThomasRS 2013-04-29 09:31:27

1

1.首先在res文件夾中創建一個目錄文件夾並將其命名爲 2.在先前創建的原始目錄文件夾內創建一個.txt文件,併爲其指定任何名稱eg.articles.txt .... 3.複印並粘貼您想要的.txt文件中創建「articles.txt」 4.dont忘記,包括您的main.xml中 MainActivity.java

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_gettingtoknowthe_os); 

    TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos); 
    helloTxt.setText(readTxt()); 

    ActionBar actionBar = getSupportActionBar(); 
    actionBar.hide();//to exclude the ActionBar 
} 

private String readTxt() { 

    //getting the .txt file 
    InputStream inputStream = getResources().openRawResource(R.raw.articles); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

    try { 
     int i = inputStream.read(); 
     while (i != -1) { 
      byteArrayOutputStream.write(i); 
      i = inputStream.read(); 
     } 
     inputStream.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return byteArrayOutputStream.toString(); 
} 

希望它的工作一個TextView文字!

0

這裏結合weekens和Vovodroid的解決方案。

它比Vovodroid的解決方案更加正確,比weekens的解決方案更完整。

try { 
     InputStream inputStream = res.openRawResource(resId); 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
      try { 
       StringBuilder result = new StringBuilder(); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        result.append(line); 
       } 
       return result.toString(); 
      } finally { 
       reader.close(); 
      } 
     } finally { 
      inputStream.close(); 
     } 
    } catch (IOException e) { 
     // process exception 
    } 
0
InputStream is=getResources().openRawResource(R.raw.name); 
BufferedReader reader=new BufferedReader(new InputStreamReader(is)); 
StringBuffer data=new StringBuffer(); 
String line=reader.readLine(); 
while(line!=null) 
{ 
data.append(line+"\n"); 
} 
tvDetails.seTtext(data.toString());