5

来自 javadoc

public String readLine()
            throws IOException

Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. 

我有以下类型的文字:

Now the earth was formless and empty.  Darkness was on the surface
of the deep.  God's Spirit was hovering over the surface
of the waters.

我正在阅读以下行:

 while(buffer.readline() != null){
       }

但是,问题是它正在考虑在换行符之前为字符串设置一行。但我想在字符串以 . 结尾时考虑行.。我该怎么做?

4

4 回答 4

7

您可以使用 aScanner并使用useDelimiter(Pattern).

请注意,输入分隔符是regex,因此您需要提供 regex \.(您需要打破.regex 中字符的特殊含义)

于 2012-04-29T17:28:41.817 回答
5

您可以一次读取一个字符,并将数据复制到 StringBuilder

Reader reader = ...;
StringBuilder sb = new StringBuilder();
int ch;
while((ch = reader.read()) >= 0) {
    if(ch == '.') break;
    sb.append((char) ch);
}
于 2012-04-29T17:25:13.003 回答
4
  • 使用 ajava.util.Scanner而不是缓冲阅读器,并将分隔符设置为"\\."with Scanner.useDelimiter()。(但请注意,分隔符已被消耗,因此您必须再次添加它!)
  • 或读取原始字符串并将其拆分为每个.
于 2012-04-29T17:28:08.903 回答
4

您可以将整个文本拆分为 every .

String text = "Your test.";
String[] lines = text.split("\\.");

拆分文本后,您会得到一组行。如果您想要更多控制,您也可以使用正则表达式,例如也可以通过:or分割文本;。只是谷歌它。

PS .:也许您必须首先使用以下内容删除换行符:

text = text.replaceAll("\n", "");
于 2012-04-29T17:28:41.367 回答