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

我搜索了如何使用目录“assets”下的资源,然后我find一个片段:

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

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

正如@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 ""; } } 

这是更好的解决方案:

 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逻辑快得多。

同意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(); }