2010-11-03 112 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());