Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

inputstream - Do any Java stream-input libraries preserve line ending characters?

I'd like to iterate through a text file one line at a time, operate on the contents, and stream the result to a separate file. Textbook case for BufferedReader.readLine().

But: I need to glue my lines together with newlines, and what if the original file didn't have the "right" newlines for my platform (DOS files on Linux or vice versa)? I guess I could read ahead a bit in the stream and see what kind of line endings I find, even though that's really hacky.

But: suppose my input file doesn't have a trailing newline. I'd like to keep things how they were. Now I need to peek ahead to the next line ending before reading every line. At this point why am I using a class that gives me readLine() at all?

This seems like it should be a solved problem. Is there a library (or even better, core Java7 class!) that will just let me call a method similar to readLine() that returns one line of text from a stream, with the EOL character(s) intact?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an implementation that reads char by char until it finds a line terminator. The reader passed in must support mark(), so if yours doesn't, wrap it in a BufferedReader.

public static String readLineWithTerm(Reader reader) throws IOException {
    if (! reader.markSupported()) {
        throw new IllegalArgumentException("reader must support mark()");
    }

    int code;
    StringBuilder line = new StringBuilder();

    while ((code = reader.read()) != -1) {
        char ch = (char) code;

        line.append(ch);

        if (ch == '
') {
            break;
        } else if (ch == '
') {
            reader.mark(1);
            ch = (char) reader.read();

            if (ch == '
') {
                line.append(ch);
            } else {
                reader.reset();
            }

            break;
        }
    }

    return (line.length() == 0 ? null : line.toString());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...