Download presentation
Presentation is loading. Please wait.
Published byBerenice Moody Modified over 9 years ago
1
Reading External Files By: Greg Patterson APCS 2010
2
Why This is Useful Java has the ability to read external data files containing numbers, strings, or really anything you want. It can then manipulate this data in a various number of ways that save time for the user. For instance, you could count the number of times “Hello” appears in a document containing 4,000 strings.
3
The Syntax In order to read external data files, the first thing that must be done, before even opening your class, is to import the following parts: import java.util.Scanner; import java.io.*; These imports enable you to import files and utilize the functions of the Scanner class.
4
Syntax cont. After opening your class and main method, the next step is to add the following line: Scanner inFile = null; Obviously the Scanner can be named whatever the code author wishes, but the generally accepted name in APCS is inFile. This line of code creates a Scanner that will be used later to read the external file into the program.
5
Syntax cont. The next (and last) block of code needed to read an external file is a try-catch statement in which the file is tried and caught only if the file named in the try statement is not found. The syntax will be on the next slide.
6
Syntax cont. try { inFile = new Scanner(new File(“fileName.ext”)); } catch (FileNotFoundException e) { System.out.print(“File not found!”); System.exit(0); } Instead of fileName.ext, you would put the name of your file. For instance Prog365h.dat. With all of this in your program and the file name spelled correctly, the program will scan and read your external file. Now let’s discuss what you can do with this.
7
Useful Methods inFile.hasNext() - This method would go in a while or do-while loop and would run as long as there is more data to be read from the file. inFile.next() - This method, reads the next bit of data from the file into the program and stores it in a String. It and its variations go hand-in-hand with the hasNext method, as when all of the data has been read, the loop will stop.
8
Useful Methods cont. inFile.nextInt() - This method reads specifically the next Integer in the file and puts it in an int variable. inFile.nextDouble() - This method reads specifically the next Double in the file and puts it in a double variable.
9
That’s all the basics about external file reading. It can take a bit of time to get used to the syntax and the functions of the different methods but after writing a few programs it becomes second nature. I hope you learned a lot from this power point and take that knowledge with you as you write your programs.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.