You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现读取文件中procedure与end之间的多行内容

Java捕获文件中procedure与end.之间的内容

你的现有代码仅捕获了包含procedure的单行,没有处理中间的多行内容,也未在遇到end.时停止捕获。可以通过以下方式实现需求:

核心思路

  • 新增布尔变量isCapturing标记是否处于目标内容区域
  • 逐行读取时,根据关键字切换捕获状态,将中间行追加到结果中
  • 使用StringBuilder替代字符串拼接,提升性能

完整代码示例

public static void main(String[] args) {
    StringBuilder piContent = new StringBuilder();
    boolean isCapturing = false;

    try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
        String line;
        while ((line = br.readLine()) != null) {
            // 遇到end.时关闭捕获,跳过该行
            if (line.contains("end.")) {
                isCapturing = false;
                continue;
            }
            // 处于捕获状态时,将当前行追加到结果(保留换行符)
            if (isCapturing) {
                piContent.append(line).append(System.lineSeparator());
            }
            // 遇到procedure时开启捕获
            if (line.contains("procedure")) {
                isCapturing = true;
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // 移除末尾多余的换行符(可选)
    if (piContent.length() > 0) {
        piContent.setLength(piContent.length() - System.lineSeparator().length());
    }

    // 输出结果
    System.out.println(piContent.toString());
}

关键细节说明

  • StringBuilder:避免频繁字符串拼接产生的性能损耗
  • System.lineSeparator():自动适配Windows/Linux等不同系统的换行符
  • 捕获逻辑顺序:先处理end.关闭捕获,再追加当前行,最后开启捕获,确保procedure和end.行不会被包含到结果中(若需要包含,可调整判断顺序)

内容的提问来源于stack exchange,提问作者papi3301

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:01:07