java - 如何优化这个字符串搜索/替换方法?

标签 java string search optimization replace

我正在实现我自己的网络服务器。以下方法搜索服务器端包含并相应地构建 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/

相关文章:

java - 调用二分查找方法的正确方法是什么

java - 排除小括号字母上的标记

java - Eclipse Oxygen 没有 MySql 的驱动程序定义

java - java.lang.Object 的 Map 的替代方案

string - 无法将类型 'Int' 的值转换为预期的参数类型 'Index'(又名 'String.CharacterView.Index')

javascript - 如何递归地查找字符串中的一组字符?

java - Ceph:通过 java 连接时 EAccess 被拒绝

c++ - Visual C++ : Migrating traditional C and C++ string code to a Unicode world

PHP mb_substr 划分错误 utf 8

algorithm - 如何有效匹配多个值