任何Java流输入库是否都保留行结束字符? [英] Do any Java stream-input libraries preserve line ending characters?

查看:246
本文介绍了任何Java流输入库是否都保留行结束字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一次迭代一行文本文件,对内容进行操作,并将结果传输到单独的文件中。 BufferedReader.readLine()的教科书案例。

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().

但是:我需要将我的行与新行粘合在一起,并且如果原始文件没有我的平台的正确换行符(Linux上的DOS文件,反之亦然)怎么办?我想我可以在流中稍微阅读一下,看看我找到了什么样的行结尾,即使这真的很糟糕。

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.

但是:假设我的输入文件没有有一个尾随换行符。我想保留它们的样子。现在我需要在阅读每个行之前先查看下一行的结尾。在这一点上,我为什么要使用一个给我 readLine()的课程?

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?

这似乎就是这样应该是一个解决的问题。是否有一个库(甚至更好的核心Java7类!)只会让我调用类似于 readLine()的方法,它从流中返回一行文本, EOL字符原封不动?

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?

推荐答案

这是一个按char读取char的实现,直到它找到一个行终止符。传入的阅读器必须支持 mark(),所以如果你没有,请将其包装在 BufferedReader 中。

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 == '\n') {
            break;
        } else if (ch == '\r') {
            reader.mark(1);
            ch = (char) reader.read();

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

            break;
        }
    }

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

这篇关于任何Java流输入库是否都保留行结束字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆