Implementing file operations

From the course: Learning Java 8

  • Course details

    Java is one of the top-five programming languages, and is used for websites, embedded controllers, and Android app development. This is an introduction to get you started programming with Java. Peggy Fisher introduces the basics: data types, strings, arrays, expressions, loops, and functions. She'll help you control the flow and logic of your code, and create classes using the principles of object-oriented design. Then go a bit beyond the basics and learn advanced techniques for working with arrays, manipulating files, and building graphical user interfaces (GUIs) that respond to user input. This three-hour capsule course is perfect for developers who need to get up to speed with Java fast, as well as for beginning programmers who want their first taste of this popular language.


    • Click here to view Peggy Fisher’s instructor page

      Peggy Fisher

      Content Strategist, Software Development Languages at Linkedin Learning Solutions with content

      Peggy Fisher is a programmer and content manager at LinkedIn Learning.

      Peggy's main focus is application programming in Java, Arduino, and C++. She has also worked on courses in COBOL and discrete ,athematics. Previously she was a faculty member at Penn State University's College of Information Sciences and Technology. She started out as a programmer working for a large insurance company, but after 18 years she left her job as a director of information technology to pursue her true passion teaching. She earned a master's degree in math education, and went on to teach high school math and computer science in Pennsylvania. In 2012, Peggy accepted a position as an instructional designer at Penn State, and shortly thereafter began teaching Intro to Application Programming with Java. She is a strong supporter of women in STEM. As one of the few female programming teachers, she serves as a mentor to incoming female freshmen who are considering a career in programming. She was also the K–12 outreach coordinator for the college, where she scheduled, ran, and taught summer camps for middle school and high school students. In a PBS NewsHour interview, she expressed that all students should take at least one programming class either in high school or college. Peggy enjoys constantly learning and finding new and exciting ways to bring technology to life in and outside of the classroom, such as using Arduino microcontrollers or Lego Mindstorms, to help make learning hands-on and fun.

    Skills covered in this course

  • Welcome

    - 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,* 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: " 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* 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.

  • Practice while you learn with exercise files

    Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.

    Download the exercise files for this course. Get started with a free trial today.

  • Download courses and learn on the go

    Watch courses on your mobile device without an internet connection. Download courses using your iOS or Android LinkedIn Learning app.

    Watch this course anytime, anywhere. Get started with a free trial today.