File I/O and Exceptions
The course is part of this learning path
This course covers how to persist data as well as how to write data from programs to file to be used later, which is called file output. We'll also learn about how to load the data from files and populate our variables with that data, which is called file input.
- Beginner coders or anyone new to Java
- Experienced Java programmers who want to maintain their Java knowledge
- Developers looking to upskill for a project or career change
- College students and anyone else studying Java
This is a beginner-level course and can be taken by anyone with an interest in learning about Java.
In this lecture, we'll combine the input and output we've learned from the last two lectures. We will read data in from not one, but two different files. One file containing names, and the other containing ages. Then we will write the age/name combinations to another file. The input files will be provided for you as student_names.txt and students_ages.txt as part of the course resources. So, let's create a file called NamesAges. So, over here, 'New', 'Java Class', NamesAges. And then, right here, we will create the obligatory main method, public static void main(String[ ] args). And then, we have that right there. And I have already copied in the student_ages.txt, which you'll see has a bunch of ages, 10 ages. And then student_names.txt.
You literally can just copy, and then paste them into the project. Right click, 'Paste' after you've copied them off of your file system or you can drag them in or do something like that, or recreate them. It doesn't really matter. I'm going to use a lot of java.io. So, java.io.File. Import java.io.FileNotFoundException. And then, import java.io.PrintWriter because we're going to need the write to file, and also java.util.Scanner. It's also important to note for the imports that if you have a bunch of stuff coming from the same package, you could actually do this. I could say, import java.io.* and then that would take care of all of these and anything else that is in that package. But I generally like to be a little more fine grained if I get to about five or six things from the same package that it may make more sense.
So, right here, I'm going to create two scanners: Scanner namesFile, Scanner agesFile, and PrintWriter pw. Or what I'm actually creating are the variables capable of holding the addresses of two scanners and one capable of holding the address of a PrintWriter object. And, of course, we need try catch. I think you probably figured that part out. try catch(FileNotFoundException). There's the end of the try catch. And then, if there is an exception, we could say, (ex.getMessage()); that will just print out the exception. Forgot the ex there. There we go.
Now it's going to complain that there's no file not found exception being thrown because we haven't written code in the try block yet. So, let's write that code, namesFile = new Scanner based on (new File, ("student_names.txt")) and then, names or rather agesFile = new Scanner(new File based on ("student_ages.txt")). And, of course, our PrintWriter; pw = new PrintWriter. This one, we just give the name directly. So, ("names_ages.txt") right there. And before we put the code in between, I like to remember to close all of these when we're done.
So, it doesn't keep a read or write lock on any of those files. Cause issues perhaps. So, I'm going to create a String tempName, and then int tempAge. And we're going to have a while loop here, and since they're the same size, we can actually just base it on one of these. We don't have to use both. So, if they were different sizes, we are doing something kind of unusual like that, we might have to use while(namesFile.hasNext()) and (agesFile.hasNext()). So, as long as both of them had something to do and then if one was longer than the other, we'd ignore the rest of it or somehow handle it another way. So, tempName; we get that using nextLine() and then we have tempAge. We read that from the agesFile.nextInt() because those are integers. And then we're going to use pw.println, and we'll print out like this. You could have chosen a different format. That's totally fine. But I'm going to put tempName, and then " is ", and then tempAge, and then " years old ". But that's really up to you how you did it.
Now, of course, let's run it. See what happens. So, we'll run the NamesAges file over here, and we don't really get any output to the screen, and that's actually or the council rather, because that's actually good. That means that there is no failure. And let's look at NamesAges.txt. And we could see the corresponding data in each file because they were parallel. So, John is 30, Bob is 15, Samantha's 22, Keegan's 25, Kyle's 13, etc. Pretty cool; that's really awesome. So, we took data and merged it from two files basically into a third file. So, that's pretty awesome.
So, it's incredibly powerful to be able to do this. And this forms fundamental ability for software developers to save and restore data as well as combining data from different sources of input to produce something different, like we just did in this particular lecture. So, before we move on, you guessed it; I've got a challenge for you. Create a new Java source file called TwiceData. Then, create a plain text file to read as input and call it nums.txt. You can just right click the project and go to new and then find empty file. Put 5 or more integers in the file, then write a program in the TwiceData class to read the integers from nums.txt into memory. And multiply those values by 2, and then print the result to a file called twice_nums.txt. So, pause the video. Come back when you're done, or if you need some help.
How did that go for you? Were you able to complete the challenge? Let's work on it together. So, we'll create the TwiceData Java file and the nums.txt. So, over here, 'src', 'New', 'Java Class', TwiceData. I'll close the other two. We'll give this void main. end main. And, of course, nums.txt. I'll right click at the top, 'New'. And we will just do new plain old 'File', and we'll call it nums.txt, and we'll put 5 or more ints in it. So, 10, 22, 55, 60, 78. So, I know I'll be using several of these. So, import java.io.FileNotFoundException. Import java.io.PrintWiter. And then, of course, java.util.Scanner. Very similar to what we did before in some ways. Scanner infile and PrintWriter pw. And we'll put a try, catch block again. The (ex.getMessage()), there we go.
And it doesn't know what file not found. It's not throwing a file not found exception yet because we did include it up here, and it'll tell us the exception or the problem that's occurring rather exception is never thrown in the corresponding try block. So, it will be in just a moment; potential for it to be thrown. infile = new Scanner based on new File, and that takes in ("nums.txt"), which is the file we created over here with our numbers. And then, we will create our PrintWriter, and this is going to be ("twice_nums.txt"). And, of course, I always like doing the close() and all of the open readers and writers, so I don't forget because that's really annoying sometimes. So, I will create int inputNum, and while(inFile.hasNext()). I will take inputNum = infile.nextInt(). We're reading a single integer from each line, and then we'll repurpose our inputNum rather to multiply by 2. So, we double the value, and then we, of course, print it to the file represented by the pw. And, of course, as always, let's run it.
So, we're going to run the TwiceData right here. There we go. And, of course, you don't see any output here. So, we're just going to go over here and look for 'twice_nums.txt'. Open it, and there we go. We've got the 5 values. You can verify that it is, in fact, twice the values in here: 10, 22, 55, and you have 20, 44, 110. And then 60 and 78; those doubled are 120 and 156. We wrote a great little program that reads input from one file, doubles the data and then writes the new values to the output file. In the next lecture, you'll get to put your newfound skills to the test as well as combining some of your knowledge that you already have in your first project for this section. A project where we'll create rectangle objects like we did earlier in the course, but this time with lengths and widths read in from file. How cool is that? So, get ready for the next exciting lecture. I'll see you there.
John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.