我有一个HTML文件如下
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="er:#css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
</head>
<body class="text" id="text">
<div class="chapter">
<a id="page1" />
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我想,以取代a id与id num和使用下面的代码.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Test {
public static void main(String[] args) throws IOException {
String input = "file:///C:/Users/users/file.html";
URL url= new URL(input);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("a id")) {
inputLine.replace("a id", "?pb label =");
}
System.out.println(inputLine);
}
in.close();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我在控制台中打印它时,它不会替换数据.我得到以下输出.
<html>
Run Code Online (Sandbox Code Playgroud)
标题
这个词没有被取代.当我这样做时debug,If-loop在这种情况下输入,数据不会在控制台中被替换.
请让我知道我哪里出错了,我该如何解决这个问题.
谢谢
String是不可改变的.您必须将返回的结果分配replace给inputLine,因为replace返回一个新的String:
inputLine = inputLine.replace("a id", "?pb label =");
Run Code Online (Sandbox Code Playgroud)