Java 缓冲读取器中的读线
来自javadocJava 缓冲读取器中的读线,java,bufferedreader,Java,Bufferedreader,来自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. 我有以下几
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){
}
<>但是,问题是,在新行之前要考虑一个字符串的行。但是,我想考虑字符串在<代码>结束时的行。< /代码>。我该怎么做?您可以一次读取一个字符,然后将数据复制到StringBuilder
Reader reader = ...;
StringBuilder sb = new StringBuilder();
int ch;
while((ch = reader.read()) >= 0) {
if(ch == '.') break;
sb.append((char) ch);
}
- 使用
而不是缓冲读取器,并使用java.util.Scanner
将分隔符设置为Scanner.useDelimiter()
。 (但请注意分隔符已被使用,因此您必须再次添加它!)“\\.”
- 或者读取原始字符串并在每个
拆分整个文本:
String text = "Your test.";
String[] lines = text.split("\\.");
分割文本后,将得到一个行数组。如果需要更多控制,也可以使用正则表达式,例如,通过:
或拆分文本代码>。只需谷歌一下
注:也许你必须先用如下方式删除新行字符:
text = text.replaceAll("\n", "");
可以使用,并使用设置自己的分隔符
请注意,输入分隔符是一个,因此需要提供正则表达式\.
(需要在正则表达式中打断字符
的特殊含义)