Bhrugesh Patel
Bhrugesh Patel

Reputation: 1106

Java data reader skips my empty new lines (\n)

Okay, I tried everything but I can't find answer. My data reader skips empty next line while reading from a txt file. It is supposed to strip all the comments from the txt file and print rest of the data as it is. My reader does strip the comments & prints the data but it skips the empty new lines..

MyDataReader.java

public String readLine()
{
    String buf = new String();
String readStr = new String();

int end = 0;
int done = 0;

try
{
    // checks if line extraction is done and marker has non null value
    while (done != 1 && marker != null)
    {
    readStr = theReader.readLine(); // Reads the line from standard input

    if (readStr != null)
    {
        /* If the first character of line isnt marker */
        if (readStr.length() > 0)
        {
            if (!readStr.substring(0, 1).equalsIgnoreCase(marker))
        {
            end = readStr.indexOf(marker);   // checks if marker exists in the string or not
            if (end > 0)
            buf = readStr.substring(0, end);
            else
            buf = readStr;

            done = 1;   // String extraction is done
         }
        }
    }
    else
    {
            buf = null;
        done = 1;
    }
    }
}
// catches the exception
catch (Exception e)
{
    buf = null;
    System.out.println(e);
}

return buf;
}

TestMyDataReader.java

String myStr = new String();

  myStr = _mdr.readLine();

  while (myStr != null)
  {
      //System.out.println("Original String : " + myStr);
      System.out.println(myStr);
      myStr = _mdr.readLine();
  }

Upvotes: 0

Views: 780

Answers (3)

Brian
Brian

Reputation: 76

Your reader won't include the newline characer in readStr, so reading in the line "\n" will make readStr be "", and

readStr.length() > 0

Will evaluate to false, thus skipping that line.

Upvotes: 1

David
David

Reputation: 3261

lots of issues in this code, but the main problem that you are dealing with is that new lines are not included in the readLine result. Thus, your if statement is not true (the line is in fact empty

Upvotes: 1

user207421
user207421

Reputation: 310936

if (readStr.length() > 0)

That's the line of code that is skipping empty lines.

Upvotes: 2

Related Questions