什么是readStream()方法?我在任何地方都找不到,

时间:2011-12-04 14:44:03

标签: android assets

我搜索了如何使用“资产”目录下的资源,然后我找到了一个代码段:

AssetManager assets = getAssets();
((TextView)findViewById(R.id.txAssets)).setText(**readStream**(assets.open("data.txt")));

我只是找不到什么是readStream方法,它不在google apis中  我试着下载最新的Java api文档,但仍然找不到它,有人知道吗?

3 个答案:

答案 0 :(得分:25)

正如@Felix所说,它是一种用户定义的方法。在您链接的页面上,他们定义了readStream,如下所示:

  private String readStream(InputStream is) {
    try {
      ByteArrayOutputStream bo = new ByteArrayOutputStream();
      int i = is.read();
      while(i != -1) {
        bo.write(i);
        i = is.read();
      }
      return bo.toString();
    } catch (IOException e) {
      return "";
    }
}

答案 1 :(得分:15)

这是更好的解决方案:

private String readStream(InputStream is) throws IOException {
    StringBuilder sb = new StringBuilder();  
    BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);  
    for (String line = r.readLine(); line != null; line =r.readLine()){  
        sb.append(line);  
    }  
    is.close();  
    return sb.toString();
}

它比 ByteArrayOutputStream 逻辑快得多。

答案 2 :(得分:3)

同意aviomaksim。

private static String readStream(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            Log.e(TAG, "IOException", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException", e);
            }
        }
        return sb.toString();
    }