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.ioclasses—no external dependencies required. - Consistent Behavior: Like the native
readLine(), this method returnsnullwhen 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
StringBuilderensures efficient character concatenation, and we're leveragingBufferedReader's built-in buffering for optimal performance.
内容的提问来源于stack exchange,提问作者GreatDuke

