This is the mail archive of the
java-discuss@sourceware.cygnus.com
mailing list for the Java project.
[patch] "\r\n" handling in DataInputStream.readLine()
- To: java-discuss@sourceware.cygnus.com
- Subject: [patch] "\r\n" handling in DataInputStream.readLine()
- From: Bryce McKinlay <bryce@albatross.co.nz>
- Date: Tue, 25 May 1999 19:12:30 +1200
While messing with Lincoln's test code, I noticed another problem. The
DataInputStream.readLine() method returns an empty string when
readLine() is called following a line terminated by an \r\n combo, such
as from a telnet session.
I have added an additional workaround to the two already implemented in
this method (but which don't work for a plain FileInputStream). The
patch sets a flag when a line is terminated with an '\r'. Readline
checks this flag when it is subsequently called, and, if set, it will
ignore the first char from the stream if that char is a '\n'.
The only case where this doesn't provide correct behaviour would be if
the user calls another DataInputStream method like read() after calling
readLine(), in which case they will still get an '\n' sitting at the
start of the stream.
regards
[ bryce ]
Index: DataInputStream.java
===================================================================
RCS file: /cvs/java/libgcj/libjava/java/io/DataInputStream.java,v
retrieving revision 1.2
diff -u -r1.2 DataInputStream.java
--- DataInputStream.java 1999/04/12 18:27:56 1.2
+++ DataInputStream.java 1999/05/25 06:45:32
@@ -21,6 +21,11 @@
public class DataInputStream extends FilterInputStream implements
DataInput
{
+ // readLine() hack to ensure that an '\r' not followed by an '\n' is
+ // handled correctly. If set, readLine() will ignore the first char
it sees
+ // if that char is a '\n'
+ boolean ignoreInitialNewline = false;
+
public DataInputStream(InputStream in)
{
super(in);
@@ -103,14 +108,29 @@
{
StringBuffer strb = new StringBuffer();
- while (true)
+ readloop: while (true)
{
- int c = read();
- if (c < 0) // got an EOF
- return strb.length() > 0 ? strb.toString() : null;
- char ch = (char) c;
- if ((ch &= 0xFF) == '\n')
- break;
+ int c = 0;
+ char ch = ' ';
+ boolean getnext = true;
+ while (getnext)
+ {
+ getnext = false;
+ c = read();
+ if (c < 0) // got an EOF
+ return strb.length() > 0 ? strb.toString() : null;
+ ch = (char) c;
+ if ((ch &= 0xFF) == '\n')
+ // hack to correctly handle '\r\n' sequences
+ if (ignoreInitialNewline)
+ {
+ ignoreInitialNewline = false;
+ getnext = true;
+ }
+ else
+ break readloop;
+ }
+
if (ch == '\r')
{
// FIXME: The following code tries to adjust the stream back one
@@ -145,7 +165,12 @@
mark(1);
if ((read() & 0xFF) != '\n')
reset();
- }
+ }
+ // In order to catch cases where 'in' isn't a BufferedInputStream
+ // and doesn't support mark() (such as reading from a Socket), set
+ // a flag that instructs readLine() to ignore the first character
+ // it sees _if_ that character is a '\n'.
+ else ignoreInitialNewline = true;
break;
}
strb.append(ch);