n_g*_*n_g 10 java bufferedreader linefeed
我写了以下代码:
public class WriteToCharBuffer {
public static void main(String[] args) {
String text = "This is the data to write in buffer!\nThis is the second line\nThis is the third line";
OutputStream buffer = writeToCharBuffer(text);
readFromCharBuffer(buffer);
}
public static OutputStream writeToCharBuffer(String dataToWrite){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(byteArrayOutputStream));
try {
bufferedWriter.write(dataToWrite);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream;
}
public static void readFromCharBuffer(OutputStream buffer){
ByteArrayOutputStream byteArrayOutputStream = (ByteArrayOutputStream) buffer;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
String line = null;
StringBuffer sb = new StringBuffer();
try {
while ((line = bufferedReader.readLine()) != null) {
//System.out.println(line);
sb.append(line);
}
System.out.println(sb);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我执行上面的代码时,以下是输出:
This is the data to write in buffer!This is the second lineThis is the third line
Run Code Online (Sandbox Code Playgroud)
为什么跳过换行符(\n)?如果我取消注释System.out.println()如下:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
sb.append(line);
}
Run Code Online (Sandbox Code Playgroud)
我得到正确的输出:
This is the data to write in buffer!
This is the second line
This is the third line
This is the data to write in buffer!This is the second lineThis is the third line
Run Code Online (Sandbox Code Playgroud)
这是什么原因?
Jig*_*shi 22
public String readLine()
throws IOException
Run Code Online (Sandbox Code Playgroud)
读一行文字.一条线被认为是由换行符('\n'),回车符('\ r')或回车符中的任何一个终止,后面紧跟换行符.
返回:
包含行内容的String,不包括任何行终止字符;如果已到达流的末尾,则
返回null 抛出:
小智 8
来自Javadoc
阅读一行文字.一条线被认为是由换行符('\n'),回车符('\ r')或回车符中的任何一个终止,后面紧跟换行符.
你可以做那样的事情
buffer.append(line);
buffer.append(System.getProperty("line.separator"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27687 次 |
| 最近记录: |