Practice Problem: Ending with a Newline

Let’s consider a text file: maybe it ends with a newline character, or maybe it doesn’t. Put another way, there may or may not be a completely empty line at the bottom of the file.

Tools like git work more smoothly with text files that end in newlines (as a reminder, I encourage all my students to use git to organize their work). Command-line tools like cat also produce clearer output when working with files that end in a newline. So, today’s Java programming problem asks you to fix files that don’t end in a newline.

I love this problem as an exam question in an introductory programming course, because it’s very easy to over-complicate your solution. Be sure to think about what you really want your code to do, before you start programming.


Practice exam problem:

Write a Java method that takes two String filenames as parameters: an input filename, and an output filename. The method must read all the contents of the input file, and write them to the output file.

But, there’s a catch: if the input file doesn’t end with a newline character ('\n'), you have to add one to the end of the output file. On the other hand, if the input file already ends in a newline, the output file should be identical to the input file.

You can assume the input file is non-empty, and your method can throw any relevant Exceptions up to the caller.

For reference: you can use a Scanner to read the input file and a PrintWriter to write the output file.


There are solutions other than the Scanner/PrintWriter combination, but using that pair of classes aligns with most introductory Java programming courses.

Do you want to see if you can simplify your solution? Working together on practice problems like this one can be part of any tutoring session. For more discussions, and to arrange for personalized tutoring for yourself or your study group, check out Vancouver Computer Science Tutoring.