2

I am learning Java. I believe I have an issue understanding how BufferedReader processes "\n" or "" strings (newline and empty strings).

If I run the following it will fail if I put either of those strings into the String array.

    String [] strings = {"55", "23", ""};
    int total = 0;
    for (String str : strings)
    {
        if (str != null) {
            total += Integer.valueOf(str);
        }
    }
    System.out.println(total);

This is fine, and makes sense to me. What does not make sense to me is when I run this code in reading in a file.

BufferedReader reader = null;
    int total = 0;
    try {
        reader = new BufferedReader(new FileReader("E:\\Testing\\Numbers.txt"));
        String line = null;
        while ((line = reader.readLine()) != null) {
                System.out.println(line);
                total += Integer.valueOf(line);
        System.out.println("Total: " + total);
    } catch(Exception e){
        System.out.println(e.getMessage());
    } finally {
        try {
            if (reader != null)
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

using a text file that has the following:

5
2
3

It runs without errors. If I add a single blank line in the same file (), it fails with the message For input string: ""

I added an isNumeric function to solve the issue, but I don't understand why the BufferedReader will work when I run the code without any empty lines, even though it does not like the "\n" or "" strings. I looked up valueOf() in the javadocs and I did not see anything that helped me.

Here is my final code that uses the isNumeric function and shows how it sees both the "\n" and "" strings as non-numeric.

    BufferedReader reader = null;
    int total = 0;
    try {
        reader = new BufferedReader(new FileReader("E:\\Testing\\Numbers.txt"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (isNumeric(line))
            {
                System.out.println(line);
                total += Integer.valueOf(line);
           }
            System.out.println("Skipping a non numeric value");
        }
        System.out.println("Total: " + total);
    } catch(Exception e){
        System.out.println(e.getMessage());
    } finally {
        try {
            if (reader != null)
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
public static boolean isNumeric(String str)
{
    try
    {
        int d = Integer.parseInt(str);
    }
    catch(NumberFormatException nfe)
    {
        return false;
    }
    return true;
}


6
Skipping a non numeric value
1
Skipping a non numeric value
Skipping a non numeric value
2
Skipping a non numeric value
62
Skipping a non numeric value
23
Skipping a non numeric value
Total: 94

Finally I did see this article on the site, and it is close, but I still could not figure it out.

Community
  • 1
  • 1
T I M
  • 83
  • 1
  • 6
  • The BufferedRaeder reads the file line by line, if the lines empty it reads an empty string. Your problem is that an empty string is not a number. You have to check the strings before parsing. – kaetzacoatl Aug 14 '16 at 18:08
  • My problem was I grouped empty and newline strings together (in my mind), but BufferedReader.readline() would return the string up to a terminating string (in this case \n) (space was not a terminating string). Sadly, I did not know if this was because of how .valueOf() worked or the readline() worked. Thank you all for your help, it got me to the answer (which was reading the readline() method in javadoc. – T I M Aug 14 '16 at 19:29

1 Answers1

2

When using a BufferedReader, the readLine() method will consume any "new line like" characters automatically.

So, in essence, your initial file was

5\n ...

And the \n is simply removed before giving the string to your code. If the line is just \n; then you get "". An easy way to check for that is line.isEmpty().

Regarding: I don't understand why the BufferedReader will work when I run the code without any empty lines; well I don't understand that question. If your code only reads lines with numbers, it doesn't matter that you have code sitting there that could deal with empty lines; or lines containing "invalid" number text.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • If I read in "5\n" as the string variable line, then Integer.valueOf(line) should give me a NumberFormatException. But when you said the readLine() method consumed, you mean BufferedReader reads a line (as the documentation says) and strips off the "\n". I had read that to mean it consumed it all and assigned it to the variable. That now makes perfect sense. Thank you! I now understand the javadoc "Returns: 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". – T I M Aug 14 '16 at 19:24
  • You are welcome. If that in deed solves your problem, feel free to accept my answer. – GhostCat Aug 15 '16 at 03:27