Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014
The simplest mechanism for reading an external text file is to use Scanner Class. You already know to use Scanner for reading console input. Instead of System.in, you first connect the file with a File object (defined in java.io package), then use that File object to construct a Scanner object. Scanner input = new Scanner(new File("input.txt")); This Scanner object (input) reads text from the file "input.txt". You can use the Scanner methods, such as next(), nextint(), nextline(), nextdouble(),to read data from the input file. input.next(); // read a string (one word only) delimited by a white-space (space, tab, newline) input.nextint(); // read an integer input.nextdouble(); // read a double input.nextline(); // read a string (the whole line) Note that the file input.txt must be in the main directory of the project, otherwise, you should specify the path of it. 2
Example: write a program to read student s information (full name, id, email, and mobile) from a file, and print them to the console. 1- Construct a Scanner object and connect the file "input.txt" using File Object. Scanner input = new Scanner(new File("input.txt")); 2- Add import statements for needed classes in external packages. Scanner defined in java.util package and File defined in java.io package, hence, add the following lines out of class body: import java.io.file; import java.util.scanner; Alternatively, use Netbeans shortcut (CTRL + SHIFT + I) to fix your imports. 3- Use Netbeans shortcuts to add throws clause for FileNotFoundException. [later you study Java Exceptions in details, but for now we do not have to know more about them] 3
Notice changes: 4- Use Scanner methods, such as nextint(), nextlong(), next(), nextline(), to read input from your file. ReadingInputFromTextFile.java import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class ReadingInputFromTextFile { public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("input.txt")); String name = input.nextline(); int id = input.nextint(); String email = input.next(); int mobile = input.nextint(); System.out.println(name); System.out.println(id); System.out.println(email); System.out.println(mobile); } } Output: 4
How Does Scanner Work? The nextbyte(), nextshort(), nextint(), nextlong(), nextfloat(), nextdouble(), and next() methods are known as token-reading methods, because they read tokens separated by delimiters. By default, the delimiters are whitespace characters. You can use the usedelimiter(string regex) method to set a new pattern for delimiters. How does an input method work? A token-reading method first skips any delimiters (whitespace characters by default), then reads a token ending at a delimiter. The token is then automatically converted into a value of the byte, short, int, long, float, or double type for nextbyte(), nextshort(), nextint(), nextlong(), nextfloat(), nextdouble(), respectively. For the next() method, no conversion is performed. If the token does not match the expected type, a runtime exception java.util.inputmismatchexception will be thrown. Both methods next() and nextline() read a string. The next() method reads a string delimited by delimiters, and nextline() reads a line ending with a line separator. The token-reading method does not read the delimiter after the token. If the nextline() method is invoked after a token-reading method, this method reads characters that start from this delimiter and end with the line separator. The line separator is read, but it is not part of the string returned by nextline(). Suppose a text file named test.txt contains a line 34 567 5
After the following code is executed, Scanner input = new Scanner(new File("test.txt")); int intvalue = input.nextint(); String line = input.nextline(); intvalue contains 34 and line contains the string " 567" (four characters ' ', 5, 6, and 7). What happens if the input is entered from the keyboard? Suppose you enter 34, press the Enter key, then enter 567 and press the Enter key for the following code: Scanner input = new Scanner(System.in); int intvalue = input.nextint(); String line = input.nextline(); You will get 34 in intvalue and an empty string in line. Why? Here is the reason. The token-reading method nextint() reads in 34 and stops at the delimiter, which in this case is a line separator (the Enter key). The nextline() method ends after reading the line separator and returns the string read before the line separator. Since there are no characters before the line separator, line is empty. You can read data from a file or from the keyboard using the Scanner class. You can also scan data from a string using the Scanner class. For example, the following code displays Scanner input = new Scanner("13 14"); int sum = input.nextint() + input.nextint(); System.out.println("Sum is " + sum); The sum is 27 6
Non-Assessed Exercise: (Evaluate simple expressions) Write a program to read 5 lines from a text file, each line representing a simple equations with one operator (*, /, +, -, %), and two operands (decimal numbers) (Ex. 5 * 6.3 ), and output the result of each one in separated line on the console. Sample input: Sample output: 7