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?
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 "";
}
}
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With