Tôi đã viết đoạn mã sau:Newline nhân vật bỏ qua khi đọc từ bộ đệm
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();
}
}
}
Khi tôi thực thi mã trên, sau đây là kết quả:
This is the data to write in buffer!This is the second lineThis is the third line
Tại sao các ký tự xuống dòng (\ n) đã bỏ qua? Nếu tôi bỏ ghi chú System.out.println() như sau:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
sb.append(line);
}
tôi nhận được đầu ra đúng như:
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
lý do cho điều này là gì?
Bỏ ghi chú 'System.out.println (dòng);' không đưa ra kết quả chính xác, cos 'System.out.println in' một chuỗi với một dòng mới. Hãy thử thay thế nó bằng 'System.out.print (line); ' –