2011-01-28 8 views
10

Ho scritto il seguente codice:Newline carattere omessi durante la lettura dal buffer

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(); 
    } 

} 
} 

Quando eseguo il codice di cui sopra, in seguito è l'output:

This is the data to write in buffer!This is the second lineThis is the third line 

Perché sono i caratteri di nuova riga (\ n) saltato? Se io rimuovere il commento le System.out.println() come segue:

while ((line = bufferedReader.readLine()) != null) { 
     System.out.println(line); 
     sb.append(line); 
     } 

ottengo l'uscita corretta come:

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 

Ciò che è motivo di questo?

+0

'System.out.println (riga) non funzionante,' non fornisce l'output corretto, cos '' System.out.println stampa' una stringa con una nuova riga. Prova a sostituirlo con 'System.out.print (riga);' –

risposta

21

JavaDoc Dice

public String readLine() 
       throws IOException 

Legge una riga di testo. Una riga viene considerata terminata da uno qualsiasi di un avanzamento riga ('\ n'), un ritorno a capo ('\ r') o un ritorno a capo seguito immediatamente da un avanzamento riga.
Returns:
una stringa contenente il contenuto della linea, ad esclusione di qualsiasi carattere line-terminazione, o null se la fine del flusso è stata raggiunta
Produce:

+1

Questo lo spiega. Molte grazie!!! –

+1

bene Jigar mi ha battuto :) – CoolBeans

+0

+1 per mettere la parte 'returns' – Nishant

8

Da Javadoc

leggere una riga di testo. Una riga viene considerata terminata da uno qualsiasi di un feed di riga ('\ n'), un ritorno a capo ('\ r') o un ritorno a capo seguito immediatamente da un avanzamento riga.

si può fare qualcosa di simile

buffer.append(line); 
buffer.append(System.getProperty("line.separator")); 
+1

+1 visto questa domanda prima di me :) –

+0

buon commento Jigar :) –

0

readline() non ritorna la fine della linea di piattaforme. JavaDoc.

0

Questo a causa di readLine(). Da Java Docs:

Leggere una riga di testo. Una riga è considerata terminata da uno qualsiasi di un avanzamento riga ('\ n'), un ritorno ('\ r') o un ritorno a capo seguito immediatamente da un avanzamento riga.

Quindi, ciò che sta accadendo è che il tuo "\ n" è considerato come un avanzamento di riga, quindi il lettore ritiene che sia una linea.

1

Questo è quello che dice il javadocs per il metodo readline() della classe BufferedReader

/** 
* Reads 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. 
* 
* @return  A String containing the contents of the line, not including 
*    any line-termination characters, or null if the end of the 
*    stream has been reached 
* 
* @exception IOException If an I/O error occurs 
*/ 
2

Solo nel caso qualcuno vuole leggere il testo con '\n' incluso.

provare questo approccio semplice

Quindi,

dire hai un tre linee dei dati (ad esempio in un file .txt), come questo

This is the data to write in buffer! 
This is the second line 
This is the third line 

E mentre leggendo, stai facendo qualcosa del genere

String content=null; 
    String str=null; 
    while((str=bufferedReader.readLine())!=null){ //assuming you have 
    content.append(str);      //your bufferedReader declared. 
    } 
    bufferedReader.close(); 
    System.out.println(content); 

e aspettando l'uscita essere

This is the data to write in buffer! 
This is the second line 
This is the third line 

ma grattarsi la testa dopo aver visto di uscita come una singola linea di

This is the data to write in buffer!This is the second lineThis is the third line 

Ecco cosa si può fare

di l'aggiunta di questo pezzo di codice all'interno del ciclo while

if(str.trim().length()==0){ 
    content.append("\n"); 
} 

Così ora che cosa il vostro ciclo while dovrebbe essere simile

while((str=bufferedReader.readLine())!=null){ 
    if(str.trim().length()==0){ 
     content.append("\n"); 
    } 
    content.append(str); 
} 

uscita ora si ottiene richiesto (come tre righe di testo)

This is the data to write in buffer! 
This is the second line 
This is the third line 
Problemi correlati