Introduction to Java: input, output, file operations

I wrote a simple console application to show you how to read from and write to text files in Java. Basically it generates two HTML files (exam results based on a data file) in two formats. There is a version for students (results sorted by student id) and a version for a teacher (sorted by result). For Java programming I recommend IntelliJ IDEA.

A data file looks like this. First name then surname, student system id and number of points achieved. An example data file:

We want to store these lines in an array of objects so there is a class with variables needed, getters and setters and some more methods I will describe later. What’s important I use comparators (needed for sorting). I need data sorted by two keys so I use two comparators.

As you can see there is a few lines commented. If you need only one way of sorting you can uncomment them and comment those two comparators instead and use the following code somewhere in your StudentApp to do the sorting.

Implementing Comparable and overriding compareTo() is just great for one sorting pattern. I needed two ways of doing it so finally I used two comparators instead.

What’s next? What actually makes the application work – a class called StudentApp. I’m creating an array list because I’m not sure how many students are in the data file. If the number was constant and known you could just use a declared array of objects. However in that case the file can be filled with any number of entries so there is need to use an array list. It’s also a structure which makes sorting really easy.

The method readFile() loads all the data to memory. It’s not a great solution when a data file is extremely big but in that case it’s ok. The second method, parseLine() extracts the values from a whole line, process them to certain variable types and finally adds objects to our array list using the class constructor.

Methods for generating files are actually easy to understand. First we sort data (that’s why we needed comparators before!) and then we create a file and write all the sorted entries there. As a result HTML files with exam results are created. It’s important to fully understand how to write to files. We need to create new BufferedWriter and we use it to write data line by line.

Last but not least – main() method where we ask for a data filename, call the methods and show what’s actually happened by printing strings in a loop thanks to overridden method toString(). That really makes displaying the lines so easy.

It's only fair to shareShare on FacebookTweet about this on TwitterShare on Google+Pin on Pinterest