Question

I am studying Scala nowadays and this is my code snippet to count the number of lines in a text file.

  //returns line number of a file
  def getLineNumber(fileName: String): Integer = {
    val src = io.Source.fromFile(fileName)
    try {
      src.getLines.size     
    } catch {
      case error: FileNotFoundException => -1
      case error: Exception => -1
    }
    finally {
      src.close()
    }
  }

I am using Source.fromFile method as explained in Programming in Scala book. Here is the problem: If my text file is like this:

baris

ayse


deneme

I get the correct result 6. If I press enter after word deneme I still get number 6, however I exptect 7 in this case. If I press space after pressing enter I get 7 which is correct again. Is this a bug in Scala standard library or more possibly am I missing something?

Finally, my basic main method here If it helps:

  def main(args: Array[String]): Unit = {
    println(getLineNumber("C:\\Users\\baris\\Desktop\\bar.txt"))
  }
Was it helpful?

Solution

It uses java.io.BufferedReader to readLine. Here is the source of that method:

/**
 * 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
 *
 * @see java.nio.file.Files#readAllLines
 */
public String readLine() throws IOException {
    return readLine(false);
}

Which calls this:

...
* @param      ignoreLF  If true, the next '\n' will be skipped
...
String readLine(boolean ignoreLF) ...
...
/* Skip a leftover '\n', if necessary */
            if (omitLF && (cb[nextChar] == '\n'))
                nextChar++;
            skipLF = false;
            omitLF = false;

So basically that's how it's implemented. I guess it depends what a line means to you. Are you counting lines that contain something or new line characters? - different things obviously.

OTHER TIPS

If you press enter after word deneme simply you add an end-of-line sequence (CR+LF, in your case) to the 6th line. You see the cursor goes to new line, but you did not create a new line: You simply specify that the sixth line is over. To create a new line you have to put a character after the end-of-line sequence, as you make when you press space.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top