File Output
File Output
1h 4m

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.

Intended Audience

  • 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 the previous lecture, we discussed file input, in which data is read from secondary storage files into main memory to be used by our programs in the form of variables. The complementary activity to reading data from file is writing data from main memory to a secondary storage file, which is called file output. This is clearly useful if we want to make the data persistent, that is, to live beyond the life of the program running in memory and even beyond when the computer is turned off. So, let's create a file named FileOutputFun. 'Right click', 'New', 'Java class' 'FileOutputFun'. There's our obligatory main method here.

Let's write some code to write some data to file. So, a couple of things we're going to need, FileNotFoundException, PrintWriter. Those both come from the package, these two classes will be used momentarily. So, we need to try-catch because in order to write to file, we have a checked exception with a (FileNotFoundException ex) that could be thrown. So, if I put PrintWriter pw = new PrintWriter, then here you don't have to pass it a file you actually can pass it the name unlike with the scanner where you had to create a new file class object as well. So, ("output.txt"); we'll call it that and before we forget, we will put pw.close();. So, pw.println, just like we have  system.out.println(), we can use this on a PrintWriter as well. ("Hello there"); and then another line ("My name is John Baugh");. If the file was not found or there's some sort of file issue, we're going to say ("Couldn't write to the file"), right there. And of course, let's run the program and see if it works. So, 'Right click' and then we go to 'Run' and you'll notice that we get this output from the IDE but we don't really see anything that's because we're not printing to the console. And apparently, it did succeed because we didn't get any error to the console, but where did it print? It printed to a file.

So, we go over here and we can see it under Project or you could go under the Project Files or Open files or whatever you'd like and ("output.txt"), and you'll notice there's a Hello there, and My name is John Baugh, and an extra new line here because these were both printed out with print line, pretty cool.

So, it looks like we're able to write to file almost as easily as we have written to console throughout the course. It's important to note that there are other classes that can be used to print to file, including buffered writer, which you may come across as well. But PrintWriter is very easy to work with, so we're using that technique here. Before moving on, I have a challenge for you. I want you to create a file named WriteNames, that is a java source file. And in this WriteNames java class, I want you to populate an ArrayList with several names, maybe five or more. Then iterate through the ArrayList and print the names to a file named names.txt. Make sure to verify that names.txt   contains the correct names that you printed. So, pause the video and try out this challenge. Return when you think you've completed the challenge or if you want to see how I've done it.

How was this challenge for you? Were you able to complete it? Let's work on it together. So, first we're going to close this and we'll make the New Java class 'WriteNames class. Perfect. Now, we're going to do public static void main(String[] args{}. And inside here, ArrayList<strings> called names, and that's a new ArrayList. It doesn't find it right away so we can actually hit 'ALT+Enter' and it will import it for us if we'd like it to do that, that's totally fine. It's good to remember what packages that these different classes live in, including ArrayList which lives in Java.util. But using the automated features is useful too. So, we'll add names.("Samantha") to the file, will add names.("John"), names.("Kyle"), names.("Heather") and names.("Luke"), and then that's being added rather to the ArrayList and then we're going to add those to the file, so we need to again have a Try-catch. If we don't have a Try-catch, it will do this. So, if I say PrintWriter pw = new. PrintWriter and say ("names.txt") like that. First of all, it doesn't know what PrintWriter is, so again, 'ALT+Enter' or you could actually click in here and if you hold down ALT or actually click the name, you can actually see that a little red icon will pop up after a couple of seconds and then you can import the class that way as well. 

So, I generally just do it in ALT+Enter and then click import class though. So, now it knows what PrintWriter is but we still have an error. If you hover over this, it says Unhandaled exception: Since that's a checked exception, we have to acknowledge it. So, the way I'm going to acknowledge it is the usually the best way, not always. We've got the 'FileNotFoundException' right here being put in a Try-catch statement. The catch I'm going to put System.out.println("can't write to file!"), kind of like we did before and in here again, pw.close(). And then in between these, we're going to put what we want to actually do. So, I'm going to use an enhanced for() range based for(), I'm going to say (String name: names) which is the identifier of the ArrayList. That's the end of the for(), we're going to say pw.println(name).

Now, you could have done each of these manually knowing the size of the Array, but what if you have 100 or 1000 or a 100,000 names? You really don't want to do all of those on separate lines when you do the printing. So, let's see now what happens when we run this. So, we're going to do 'Right click' on 'WriteNames' and then we're going to go to 'Run' and again we get this automatic IDE Output and you'll notice there's a nice new file here called names.txt. So, 'Double click' that and we have Samantha, John, Kyle, Heather and Luke, and our extra space at the end. Awesome, great work everyone. In the next lecture, we'll do some practicing with both file input and file output to strengthen our understanding. Let's get going.


About the Author
Learning Paths

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.

Covered Topics