Search code examples
javaiobufferedreader

Difference in File Output Between Hard Coded Filepath and Passing as Command Line Argument


So, I am writing a program where I am reading from a file one character at a time, doing an operation with the character, then writing the output to a different file.

For some reason I get a different result when I hard code the file path (I did that just so I didn't have to keep typing the file while debugging) and when I pass the files from the command line.

When I pass the file from the command line it will skip input lines sometimes, so if I had a file with 10 lines I may only get 8 lines being processed.

I have a feeling it has something to do with whether or not there are spaces at the end of the input lines but I can't seem to figure it out. Any help would be much appreciated.

Also, I was using NetBeans when I hardcoded the file path, and ran the program from the terminal when I used command-line arguments. I have pasted the I/O code below.

while( ( i = buffRead.read() ) != -1 )
{
    try
    {

        char c = (char) i;

        if ( Character.isWhitespace(c) )
        {
            if(converter.getStackSize() > 1)
            {
                converter.resetConverter();
                throw new IncorrectNumOfOperandsException();
            }

            buffRead.readLine();
            converter.resetConverter();
            writeOut.println();

        }
        else
        {
            converter.register( c );
        }
    }
    catch (InvalidCharException j)
    {
        writeOut.println("Invalid Character Entered\n");
        buffRead.readLine();
    }
    catch (IncorrectNumOfOperatorsException k)
    {
        writeOut.println("Too Many Operators for Number of Operands\n");
        buffRead.readLine();
    }
    catch ( IncorrectNumOfOperandsException m)
    {
        writeOut.println("Too Many Operands for Number of Operators\n");
        buffRead.readLine();
    }

}


buffRead.close();
writeOut.close();        

Solution

  • I think I see the problem.

    You test c to see if it is a whitespace character, and if it is, you then call readLine(). What readLine() does is to read one or more characters until it gets to the next end-of-line sequence.

    So what happens when c contains a newline character?

    • newline is a whitespace character (look it up)
    • so you read a line, starting at the first character after the newline that you just read
    • and discard the line.

    So you have (accidentally) thrown away a complete line of input.

    The solution ... I will leave to you.

    When I pass the file from the command line it will skip input lines sometimes ...

    I suspect that the same behavior was happening when you were typing the input ... but you didn't notice it. But it is possible that there is something going on with platform specific line termination sequences.