gpt4 book ai didi

java - 字符串操作在android上挂起?

转载 作者:行者123 更新时间:2023-12-02 08:11:01 25 4
gpt4 key购买 nike

我正在编写一个 Android 应用程序,它要求我检索网页的 html 代码并获取并返回特定元素。由于某种原因,代码似乎挂起或花费令人难以置信的长时间来执行基本字符串操作。

    URL url = new URL(link);
URLConnection urlConnection = url.openConnection();
InputStreamReader i = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader in = new BufferedReader(i);
String check = "";
String html = "";
while((check = in.readLine()) != null)
html += check;

在模拟器和具有大学连接速度的设备上只需几分钟即可完成。鉴于

    URL url = new URL(link);
URLConnection urlConnection = url.openConnection();
InputStreamReader i = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader in = new BufferedReader(i);
String check = "";
String html = "";
int p = 0;
while((check = in.readLine()) != null)
p++;

大约需要 5 秒并返回 html 页面中正确的行数。为什么字符串操作需要这么长时间?仅出于透视目的,该页面大约有 4000 行长。

最佳答案

因为你做错了。使用StringBuilder构建大型字符串。

StringBuilder sb = new StringBuilder();
while((check = in.readLine()) != null)
sb.append(check);
html = sb.toString();

Why StringBuilder when there is String?

String does not allow appending. Each method you invoke on a String creates a new object and returns it. This is because String is immutable - it cannot change its internal state.

关于java - 字符串操作在android上挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7425606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com