gpt4 book ai didi

java - 当我向字符串追加字符时,如何删除 "null"单词?

转载 作者:行者123 更新时间:2023-12-01 19:36:09 25 4
gpt4 key购买 nike

我正在尝试打印网站的 HTML 页面源代码。我在第 45 行将字符串初始化为 null。但是,当我尝试打印新附加的字符串时,会显示 null 关键字。

我尝试删除 String 的初始化。

 public class MainActivity extends AppCompatActivity {
public class ToPrintWebSiteSource extends AsyncTask<String,Void,String>{
@Override
HttpURLConnection httpURLConnection = null;
String result = null;
try {
siteUrl = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) siteUrl.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data!= -1){
char character = (char) data;
result += character;
data = reader.read();
}
}
catch (Exception e) {
Log.i("Error:","The code is not working....");
e.printStackTrace();
}
return result;

}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result = null;
ToPrintWebSiteSource helloWorld = new ToPrintWebSiteSource();
try {
result = helloWorld.execute("https://web.ics.purdue.edu/~gchopra/class/public/pages/webdesign/05_simple.html").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Page Source Html:", result);
}
}

我收到的结果是:

null<html>

<head>
<title>A very simple webpage</title>
<basefont size=4>
</head>

最佳答案

您应该将其设置为空字符串而不是 null。当您将字符串与 null 连接时,字符串“null”将添加到其中,而不是空。

更好的是,您甚至不应该在此处使用字符串连接。这就是 StringBuilder 的用途。

    HttpURLConnection httpURLConnection = null;
StringBuilder result = new StringBuilder();
char buffer[] = new char[100];

try {
siteUrl = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) siteUrl.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);

for (int n; (n = reader.read(buffer)) != -1;) {
result.append(buffer, 0, n);
}
}
catch (Exception e) {
Log.i("Error:","The code is not working....");
e.printStackTrace();
}
return result.toString();

这一次将多个字符读入一个字符数组,将字符附加到StringBuilder,直到读取所有数据。将数组的大小设置为 100 是任意的,如果您想一次读取更多数据,可以将其设置得更大。

关于java - 当我向字符串追加字符时,如何删除 "null"单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463059/

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