Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the readStream() method? i just can not find it anywhere,

Tags:

android

assets

i searched how to use resources under the directory "assets", then i find a snippet:

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

i just cannot find what's the readStream method, it is not in the google apis i tried to download the newest Java api document, but still can not find it, anybody knows that?

like image 519
Y.L. Avatar asked Dec 04 '11 14:12

Y.L.


3 Answers

As @Felix said it is a user-defined method. On the page you linked, they defined readStream like this:

  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 "";
    }
}
like image 65
Chris Avatar answered Oct 04 '22 15:10

Chris


This is better solution:

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

It is much faster than ByteArrayOutputStream logic.

like image 35
aviomaksim Avatar answered Oct 04 '22 17:10

aviomaksim


Agree with 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();
    }
like image 3
macio.Jun Avatar answered Oct 04 '22 17:10

macio.Jun