Join Peggy Fisher for an in-depth discussion in this video Implementing file operations, part of Learning Java.
- Up until now, we've been reading data directly from the console using the Scanner class. Now let's see how we can read data from a file. By importing the libraries included, using the wildcard, java.io.* This allows us to read from a file, write to a file or even create a new file. In this program, we will read possible replies to a random question asked by the user: A type of "fortuneTeller" program. To open and read from a file, we need to follow these steps: Step One is to create a file object that specifies the filename, including the extension.
Right here, I have "File_InputFile". "InputFile" is my variable name, equals "new_File", and the name of my file is "answers.txt" Let's take a quick look at that file. Right now, it has 10 random answers. These are the answers that the program will use to reply to the customer's question. I do wanna point out that the file has to be in the same location as the "build.xml" file. Okay, let's go back to our program.
The next thing I do is create an arraylist called "answers" of type = [String] "answers = new ArrayList[String]()" And I'm gonna use a random number generator to randomly select the answer. Let me scroll down a little bit. Step Two when using files is to use the Scanner class to declare an object that will allow me to read from the file. So in Line 24, I have: "Scanner_Input = new Scanner", and in parenthesis, I have: "(inputFile)" Remember, that's the variable name that I gave my "answers.txt" file.
Okay, let's finish walking through the program. After I create the Scanner input, I can use that in my "while" loop to check and see if there's any more answers in the file. This is done using the "hasNextLine" command. So: "while input.hasNextLine", meaning: "If there's more information in the file, "I'll read that value into my variable called 'answer', "and then I'll add that to my array called 'answers'." But right now, I'm gonna skip over the Try and Catch.
I'll talk about that in a second. Down below, I added some code to allow the user to repeat the fortune telling program as well as, I have a message that tells them: "The fortune teller is ready for you. "Please think about your question in your mind "and hit enter for your reply." When they hit "Enter", Line 42 will read-in the "Enter" symbol; it just won't do anything with it. And then I'll print out the answer using the random number generator. Okay, before I run the program, let me just quickly talk about Try and Catch.
Try and Catch are required when you're working with files. They allow us to nicely handle an exception. So, you can see here, I have the "try" right before the part where I try and read from the inputFile. What happens is: if the inputFile does not exist, it'll fall into this "catch" portion, and it'll print out a message saying: "The file is not found." And it'll print out the information about the error. Okay, let's give our fortuneTeller program a try. Alright, let's think of a question.
"Is it going to rain today?" When I hit "Enter", the fortuneTeller says: "Without a doubt." Aw, bummer, guess I need an umbrella. Okay, we're gonna go ahead and say 'No' here, but you could keep going if you wanted to. I wanna go back to my program real quick and show you what would happen if I changed the text file to just be "answer.txt" This time, the program will not find the file. It starts out by saying: "The input file 'answers.txt' was not found." It gave me an error saying: "java.io.FileNotFoundException: answers.txt "(The system cannot find the file specified)" So that way, we catch the error and it does not cause my program to abort.
Okay, next, let's take a look at an example program that writes to a file. Mine's called: "CustomerNames". In this program, I'm gonna ask the user to enter a list of customer names and I'm going to save them to a file so I have them for later use. I'm still including: import java.io.* In my program on Line 19, I create a variable name called "output" that represents my file, and I give the file a name: "customers.txt" It is important to mention that writing to a file that does not exist will create a new file.
It will not cause an error. Also, if there already is a file, it will erase the contents and create an empty file. Okay, in my program, on Line 21, I'm asking the user to enter in the customer name, and I still have a Try and Catch, here, to handle any unexpected errors. This is a little different. In Line 24, I'm creating a PrintWriter object which is different than the Scanner we were using earlier. This is what you'll use when you want to create files or write to files.
I'm giving it a name of "out". I have "PrintWriter out = new PrintWriter", and in parenthesis, I have: "(output)", which is the name of my customers.txt file. When the user types in the word "done", we'll get out, but until they do, I'm using Line 27 to write the name to the output file. So I use the PrintWriter object "out.println", and in parenthesis, I put: "(name)" I ask the user to: "Type in any more names or \'done\' to exit." Now, Line 31 is very important.
"out.close" This closes the PrintWriter file. If you forget to include "out.close", chances are, all of your information will still be in the buffer when your program ends, and when you open the file, it'll be empty. So please keep that in mind. You wanna make sure that if you're writing to a file that you close the file before exiting your program. Let's run this program. I'm gonna enter in the name of a few customers. Okay, now I'm gonna type 'done'. It says: "BUILD SUCCESSFUL", but at this point I don't know; I need to go look at my file.
So let's go to the Windows Explorer. I need to go back to NetBeansProjects, I need to open up my CustomerNames project, and there's my file. If I open up my "customers" file, you can see: Peggy Fisher, Joe Smith, John Knapp and Sue Sutherland are there. Hopefully, this helps you see how important it is to know how to read and write files in programming.
- Downloading and exploring NetBeans
- Understanding Java basics: data types, strings, arrays, and more
- Controlling flow with functions and loops
- Creating classes
- Sorting and searching arrays
- Manipulating files
- Handling errors
- Building GUIs