java 缓冲阅读器读取文本直到字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30832101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:43:15  来源:igfitidea点击:

Buffered Reader read text until character

javafilewhile-loopbufferedreaderreadline

提问by Waggoner_Keith

I am using a buffered reader to read in a file filled with lines of information. Some of the longer lines of text extend to be more than one line so the buffered views them as a new line. Each line ends with ';'symbol. So I was wondering if there was a way to make the buffered reader read a line until it reaches the ';'then return the whole line as a string. Here a how I am using the buffered reader so far.

我正在使用缓冲阅读器来读取充满信息行的文件。一些较长的文本行扩展到不止一行,因此缓冲将它们视为新行。每行以';'符号结尾。所以我想知道是否有办法让缓冲读取器读取一行直到它到达';'然后将整行作为字符串返回。这是到目前为止我如何使用缓冲阅读器。

  String currentLine;
        while((currentLine = reader.readLine()) != null) {
            // trim newline when comparing with lineToRemove
            String[] line = currentLine.split(" ");
            String fir = line[1];
            String las = line[2];
            for(int c = 0; c < players.size(); c++){
                if(players.get(c).getFirst().equals(fir) && players.get(c).getLast().equals(las) ){
                    System.out.println(fir + " " + las);
                    String text2 = currentLine.replaceAll("[.*?]", ".150");
                    writer.write(text2 + System.getProperty("line.separator"));
                }
            }
        }

回答by Mureinik

It would be much easier to do with a Scanner, where you can just set the delimiter:

使用 a 会容易得多Scanner,您可以在其中设置分隔符:

Scanner scan = new Scanner(new File("/path/to/file.txt"));
scan.useDelimiter(Pattern.compile(";"));
while (scan.hasNext()) {
    String logicalLine = scan.next();
    // rest of your logic
}

回答by John

To answer your question directly, it is not possible. Buffered Reader cannot scan stream in advance to find this character and then return everything before target character.

要直接回答您的问题,这是不可能的。Buffered Reader 不能提前扫描流来找到这个字符,然后返回目标字符之前的所有内容。

When you read from stream with Buffered Reader you are consuming characters and you cannot really know character without reading.

当您使用 Buffered Reader 从流中读取时,您正在消耗字符,并且不阅读就无法真正了解字符。

You could use inherited method read()to read only single character and then stop when you detect desired character. Granted, this is not good thing to do because it contradicts the purpose of BufferedReader.

您可以使用继承方法read()仅读取单个字符,然后在检测到所需字符时停止。当然,这不是一件好事,因为它与 BufferedReader 的目的相矛盾。