Java ArrayListsReading data from files is a fast way to do many types of work.
Visit Java User Input to see a Scanner example.
To read from a file, you will need to add at least two imports to the top of your class:
import java.io.File; import java.util.Scanner;
Now you can create a File object (perhaps in your main() method) that points to a file in your project folder:
File f = new File("myfile.txt");
Note: you have to actually create this text file (use Notepad or whatever).
Put it in your project folder with your Java code files if you are using BlueJ.
If you are using something fancier like IntelliJ IDEA, and you have a directory structure in your project, you have to include the folders in your file name.
Example for file in a subdirectory from a typical IntelliJ project:
f = new File("src/com/company/myfile.txt");
Next you can create a Scanner object. Instead of using “System.in” for your scanner, use the file.
scan = new Scanner(f);
You will find that Java complains about an “unreported exception” if you use the previous line of code as is.
You have to surround this Scanner with try / catch to fix this problem:
try { scan = new Scanner(f); } catch (Exception e){ System.out.println("Exception caught:"); System.out.println(e); }
Java has trust issues – it doesn’t know if the file (“myfile.txt” in this case) will actually be there, so it forces the programmer to account for the possibility that the file is not found.
When you create this program, you must actually create a text file (use Notepad or whatever) and put it in your project folder with the Java code files. If it’s in a subfolder (subdirectory), you can refer to it like this:
If Java tries to create the scanner on File f and it isn’t there, it will go to the catch branch and print the exception (i.e. the error).
Note that try/catch is similar to if/else . Try/catch chooses which branch’s code block to execute according to whether an exception (error) occurred, whereas if/else chooses based on a boolean condition.
Using the Scanner: now that the Scanner is created, you can use the same methods to read input:
//read one line(String) and point to next line //(you can run this repeatedly to see all lines) scan.nextLine(); //check if a next line exists (boolean) scan.hasNext();
You can use hasNext() and nextLine() to loop through the entire file:
String line; while (scan.hasNext()){ line = scan.nextLine(); System.out.println(line); }
That example simply prints out every item.
You could instead add every item to an ArrayList, for example.
(See ArrayLists)