我正在实现我自己的网络服务器。以下方法搜索服务器端包含并相应地构建 html 页面。
public String getSSI(String content) 抛出 IOException {
String beginString = "<!--#INCLUDE VIRTUAL=\"";
字符串 endString = "\"-->";
int beginIndex = content.indexOf(beginString);
while (beginIndex != -1) {
int endIndex = content.indexOf(endString, beginIndex);
String includePath = content.substring(beginIndex+beginString.length(), endIndex);
文件 includeFile = 新文件(BASE_DIR+includePath);
byte[] bytes = new byte[(int) includeFile.length()];
FileInputStream in = new FileInputStream(includeFile);
in.read(字节);
附寄();
字符串包含内容=新字符串(字节);
包含内容 = getSSI(包含内容);
内容 = content.replaceAll(beginString+includePath+endString, includeContent);
beginIndex = content.indexOf(beginString);
}
返回内容;
}
我知道 StringBuilder 比 String 更快,但这就是我能做的一切来优化它吗?原始数据被读入字节数组并转换为字符串,然后将其传递给此方法,然后将输出转换回字节数组并发送给客户端。
最佳答案
我不知道这会产生多大的影响,但是您可以使用IOUtils toString(InputStream),而不是读入字节数组并转换为字符串。方法直接读取字符串。同样,您可以 write the String directly to an OutputStream .
关于java - 如何优化这个字符串搜索/替换方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16116110/