Bug in java.io.RandomAccessFile.readLine()

Juergen Sonnauer sonic at az-online.net
Sat Oct 24 07:15:03 PDT 1998


Marc Jauvin wrote:
> I discovered a bug in the readLine() method in 'java.io.RandomAccessFile'; the
> problem was caused by trying to cast an int value into a byte. It might not have
> caused problem on some architectures, but it did on x86... one other thing, the
> '\r' and '\n' were returned as part of the string, which is not the behavior of
> the implementation in java.io.BufferedReader.readLine()  (neither it is in SUN's
> jdk if I remember correctly by USING their readLine() functions)

Your patch can be adapted for the java.io.DataInputStream class. So here it is.

Regards,
Juergen
-------------- next part --------------
--- kaffe-snap/libraries/javalib/java/io/DataInputStream.java	Tue Oct 13 07:16:59 1998
+++ DataInputStream.java	Sat Oct 24 15:55:26 1998
@@ -82,45 +82,30 @@
 final public String readLine() throws IOException
 {
 	StringBuffer buffer = new StringBuffer();
+	int nread = 0;
 
-	for (;;) {
-		int data = super.read();
+	while (true) {
+		final int data = read();
+		final char ch = (char) (data & 0xff);
 
-		if (data == -1) {
+		if (data == -1)
 			break;
-		}
+		nread++;
 
-		char cdata = (char)data;
-		if (cdata == '\n') {
+		if (ch == '\n')
 			break;
-		}
-		if (cdata == '\r') {
-			/* Check for "\r\n" */
-			super.mark(1);
-			data = super.read();
+		if (ch == '\r') {	// Check for '\r\n'
+			mark(1);
+			final int data2 = read();
+			final char ch2 = (char) (data & 0xff);
 
-			if (data == -1) {
-				break;
-			}
-
-			cdata = (char)data;
-			if (cdata != '\n') {
-				/* Jump back to mark */
-				reset();
-			}
+			if (data2 != -1 && ch2 != '\r')
+				reset();        // Jump back to mark
 			break;
 		}
-		else {
-			buffer.append(cdata);
-		}
-	}
-
-	if (buffer.length() == 0) {
-		return (null);
-	}
-	else {
-		return (buffer.toString());
+		buffer.append(ch);
 	}
+	return (nread == 0) ? null : buffer.toString();
 }
 
 final public long readLong() throws IOException {


More information about the kaffe mailing list