As we start to use our programs to analyze more and more information, having a way to import and export information becomes critical. This is where file input and output become important. In this tutorial, we are going to look at a few things. First, we are going to take a look at how we read in lines from a file. We will then look at some very basic string manipulation to split our lines. Finally, we will look at how we can write out results to a file.
The basic process to read in from file is the following:
Scanner
object using the input fileOne thing to note is that we need to do this inside of a try/catch block. We will not be looking at the try/catch block functionality today, but not that it is required by Java anytime we read in a file.
Let’s take a look at these steps below.
Notice in the example on line 21, we use the hasNext()
command and on line 24, we use the nextLine()
command. The hasNext()
command returns a boolean as to whether there are more lines to read. If there are, the program continues to loop and then reads in that next line using the nextLine() command. Notice that we create a string variable called lineIn
to read this value each time through the loop.
Different files may contain different information and we may not just want each line to be its own string variable. The two most common things that we would need to do with a file input are splitting the line into pieces and transforming a string into a number. Below is an example, of how we might do this to sum lines of integer,
Writing to an output file is similar to our input. The most common way to do this in Java is using the print writer. After importing the PrintWriter
, we simply create a new file, write to it using println
commands and then close it.
In our example, we will not be able to see the file once created but to verify that it is there, we will read it back in and print out the results. Try changing line 15 below and see the impact that it has.
Now it is your turn to try! Read in the input file and add the value to a sum. Print out this sum each time you read in a new file. For example: