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

Java如何基于指定行终止符实现自定义按行读取文本文件?

Custom readLine Implementation with a Custom Terminator in Java

Absolutely you can implement a custom line-reading method tailored to your specific terminator—no external libraries needed, just leveraging Java's core IO classes. Here's a straightforward approach by extending BufferedReader (since it already handles efficient character reading under the hood):

Step-by-Step Implementation

We'll create a custom reader class that adds a readLineModified(char lineTerminator) method. This method will read characters one by one, accumulate them in a StringBuilder, and return the accumulated content whenever it hits your specified terminator (or when the stream ends).

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

public class CustomLineReader extends BufferedReader {

    public CustomLineReader(Reader in) {
        super(in);
    }

    public String readLineModified(char lineTerminator) throws IOException {
        StringBuilder lineBuilder = new StringBuilder();
        int currentChar;

        // Read characters one by one until we hit the terminator or end of stream
        while ((currentChar = read()) != -1) {
            char c = (char) currentChar;
            if (c == lineTerminator) {
                // Return the accumulated line (excluding the terminator)
                return lineBuilder.length() > 0 ? lineBuilder.toString() : "";
            }
            lineBuilder.append(c);
        }

        // If we've reached end of stream and have accumulated characters, return them
        return lineBuilder.length() > 0 ? lineBuilder.toString() : null;
    }
}

How to Use It

Let's test this with your sample input "Foo foo $ bar bar $ foobar jonathan" (using $ as the terminator):

import java.io.StringReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        String input = "Foo foo $ bar bar $ foobar jonathan";
        try (CustomLineReader reader = new CustomLineReader(new StringReader(input))) {
            String line;
            while ((line = reader.readLineModified('$')) != null) {
                // Trim any leading/trailing whitespace if needed (matches your sample output)
                System.out.println("'" + line.trim() + "'");
            }
        }
    }
}

Output

'Foo foo'
'bar bar'
'foobar jonathan'

Key Notes

  • No Special Modules: This uses only Java's standard java.io classes—no external dependencies required.
  • Consistent Behavior: Like the native readLine(), this method returns null when the end of the stream is reached, making it easy to integrate into existing loop patterns.
  • Edge Cases Handled: It correctly handles empty segments (if two terminators are back-to-back) and the final line that doesn't end with the terminator.
  • Efficiency: Using StringBuilder ensures efficient character concatenation, and we're leveraging BufferedReader's built-in buffering for optimal performance.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:49:29