Android 从输入流中高效读取 [英] Android Reading from an Input stream efficiently
问题描述
我正在向网站发出 HTTP get 请求以获取我正在制作的 Android 应用程序.
我正在使用 DefaultHttpClient 并使用 HttpGet 发出请求.我得到实体响应,并从中获取一个 InputStream 对象以获取页面的 html.
然后我按如下方式循环回复:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));字符串 x = "";x = r.readLine();字符串总数 = "";while(x!= null){总计 += x;x = r.readLine();}
然而这是非常缓慢的.
这是低效的吗?我没有加载一个很大的网页 - www.cokezone.co.uk 所以文件大小并不大.有没有更好的方法来做到这一点?
谢谢
安迪
您的代码中的问题在于它创建了大量繁重的 String
对象,复制它们的内容并对它们执行操作.相反,您应该使用 StringBuilder
来避免在每次追加时创建新的 String
对象并避免复制字符数组.您的案例的实现将是这样的:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));StringBuilder total = new StringBuilder();for (String line; (line = r.readLine()) != null; ) {total.append(line).append('
');}
您现在可以使用 total
而无需将其转换为 String
,但如果您需要将结果作为 String
,只需添加:>
String result = total.toString();
我会尽量解释得更好...
a += b
(或a = a + b
),其中a
和b
是字符串, 将 botha
和b
的内容复制到一个新的对象中(注意你也复制了a
,其中包含 accumulatedString
),并且您在每次迭代时都进行这些复制.a.append(b)
,其中a
是一个StringBuilder
,直接将b
内容追加到a
,因此您不会在每次迭代时复制累积的字符串.
I am making an HTTP get request to a website for an android application I am making.
I am using a DefaultHttpClient and using HttpGet to issue the request. I get the entity response and from this obtain an InputStream object for getting the html of the page.
I then cycle through the reply doing as follows:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String x = "";
x = r.readLine();
String total = "";
while(x!= null){
total += x;
x = r.readLine();
}
However this is horrendously slow.
Is this inefficient? I'm not loading a big web page - www.cokezone.co.uk so the file size is not big. Is there a better way to do this?
Thanks
Andy
The problem in your code is that it's creating lots of heavy String
objects, copying their contents and performing operations on them. Instead, you should use StringBuilder
to avoid creating new String
objects on each append and to avoid copying the char arrays. The implementation for your case would be something like this:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
for (String line; (line = r.readLine()) != null; ) {
total.append(line).append('
');
}
You can now use total
without converting it to String
, but if you need the result as a String
, simply add:
String result = total.toString();
I'll try to explain it better...
a += b
(ora = a + b
), wherea
andb
are Strings, copies the contents of botha
andb
to a new object (note that you are also copyinga
, which contains the accumulatedString
), and you are doing those copies on each iteration.a.append(b)
, wherea
is aStringBuilder
, directly appendsb
contents toa
, so you don't copy the accumulated string at each iteration.
这篇关于Android 从输入流中高效读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!