Bufferedreader 一次不读取整行?
Bufferedreader doesn't read the whole line at a time?
我正在使用 BufferedReader
使用 Bufferedreader.readLine()
逐行读取文本文件,但突然它没有读取整行而是只读取第一个字符串
示例:如果文本文件中的第一行是:
[98.0,20.0,-65.0] [103.0,20.0,-70.0] 5.0 [98.0,20.0,-70.0] ccw
我的代码是:
BufferedReader br = new BufferedReader(new FileReader("path" + "arcs.txt"));
String Line = br.readLine();
System.out.println(Line):
输出将是:
[98.0,20.0,-65.0]
为什么会这样?
BufferedReader
内部工作方式如下:
InputSream 或 InputFile 字符流将被缓冲,直到出现 \n
(换行)或 \r
(回车 return)实例。如果不出现这两个字符之一,BufferedReader
将陷入 while 循环。这种情况的一个例外是,当输入字符流关闭时。因此,为什么它提前 returning 的唯一合理解释必须是,在该行的第一位之后有某种行结束字符。为确保捕获文件中的所有内容,您可以添加一个环绕的 while 循环。
示例:
// Please ignore the fact that I am using the System.in stream in this example.
try(BufferedReader br = new BufferedReader( new InputStreamReader( System.in) ))
{
String line;
StringBuilder sb = new StringBuilder();
// Read lines until null (EoF / End of File / End of Stream)
while((line = br.readLine()) != null)
{
// append the line we just read to the StringBuilds buffer
sb.append(line);
}
// Print the StringBuilders buffer as String.
System.out.println(sb.toString());
}
catch ( IOException e )
{
e.printStackTrace();
// Exception handling in general...
}
缓冲区 reader 的 readLine() 方法读取一个字符串,直到它到达一个行分隔符,例如 \n 或 \r。您的文本文件必须在 [98.0,20.0,-65.0] 之后具有这些标记。
我正在使用 BufferedReader
使用 Bufferedreader.readLine()
逐行读取文本文件,但突然它没有读取整行而是只读取第一个字符串
示例:如果文本文件中的第一行是:
[98.0,20.0,-65.0] [103.0,20.0,-70.0] 5.0 [98.0,20.0,-70.0] ccw
我的代码是:
BufferedReader br = new BufferedReader(new FileReader("path" + "arcs.txt"));
String Line = br.readLine();
System.out.println(Line):
输出将是:
[98.0,20.0,-65.0]
为什么会这样?
BufferedReader
内部工作方式如下:
InputSream 或 InputFile 字符流将被缓冲,直到出现 \n
(换行)或 \r
(回车 return)实例。如果不出现这两个字符之一,BufferedReader
将陷入 while 循环。这种情况的一个例外是,当输入字符流关闭时。因此,为什么它提前 returning 的唯一合理解释必须是,在该行的第一位之后有某种行结束字符。为确保捕获文件中的所有内容,您可以添加一个环绕的 while 循环。
示例:
// Please ignore the fact that I am using the System.in stream in this example.
try(BufferedReader br = new BufferedReader( new InputStreamReader( System.in) ))
{
String line;
StringBuilder sb = new StringBuilder();
// Read lines until null (EoF / End of File / End of Stream)
while((line = br.readLine()) != null)
{
// append the line we just read to the StringBuilds buffer
sb.append(line);
}
// Print the StringBuilders buffer as String.
System.out.println(sb.toString());
}
catch ( IOException e )
{
e.printStackTrace();
// Exception handling in general...
}
缓冲区 reader 的 readLine() 方法读取一个字符串,直到它到达一个行分隔符,例如 \n 或 \r。您的文本文件必须在 [98.0,20.0,-65.0] 之后具有这些标记。