Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
ALIGARH MUSLIM UNIVERSITY Department of Computer Science Course: MCA CSM-2002: Object Oriented Programming Using JAVA Academic Session 2016-2017 Handout-10 Dr. Rafiqul Zaman Khan, Professor (Computer Science). ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Objectives: • To gain practical experience on using File I/O Reading Input from a file: To read input from a file, we make use of the following classes from the java.io package: FileReader: This is used to create an object that can be used to read one character from a file. BufferedReader: This can be used together with a FileReader object to read one line from a text file. BufferedReader in = new BufferedReader(new FileReader(“inputfile.txt”)); As we all know, the BufferedReader object has a readLine() that returns a string. When used to read a file, the readLine( ) method returns a whole line. It returns null if there is no more data in the file. Notes: • If the file does not exist, a FileNotFoundException is thrown. • If the file is not in the current folder, the full path of the file must be specified. • When specifying the full path of the file, it is better to use forward slash. Example: “C:/workarea/inputfile.txt” • The back slash can also be used, but double slash must be used for each slash. Example: “C:\\workarea\\inputfile.txt” Example#1: The following example reads one line at a time from a file and prints it on the screen. import java.io.*; class TestBufferedReader { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader ( new FileReader ("inputfile.txt") ); String s=in.readLine(); while (s != null) { System.out.println(s); s=in.readLine(); 1 } in.close(); } } Writing/Appending output to text files: To write or append output to a file, we make use of the following classes from the java.io package: FileWriter: This is used to create an object that can be used to write one character to a file. PrintWriter: To be able to write/append strings, we create a PrintWriter object, passing a FileWriter object as a parameter: PrintWriter out = new PrintWriter(new FileWriter(“result.txt”)); //for writing or PrintWriter out = new PrintWriter(new FileWriter(“result.txt”, true)); //for appending The PrintWriter object has print() and println() methods that behave in exactly the same manner as those of System.out object. Notes: • Unlike the case of FileReader object, if the file does not exist, it is created automatically. However, if there is no writing access to the file or its folder, a FileNotFoundException is thrown. Example#2: The following example reads one line at a time from an input file and prints it to an output file. import java.io.*; public class TestFiles { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader( new FileReader("inputfile.txt")); PrintWriter out = new PrintWriter( new FileWriter("outputfile.txt")); String s=in.readLine(); while (s != null) { out.println(s); s=in.readLine(); } in.close(); 2 out.close(); System.out.println("File copied successfully"); } } Example#3: A text file named NamesIDs.txt contains Student IDs and corresponding Students’ Names in separate lines, for some number of students. The following program reads Student IDs and Names from that text file NamesIDs.txt and then it prints only the IDs in the output file IDs.txt and the Names in the output file Names.txt // FileSplitter.java /* This program Reads from an input file and Prints in two files. */ import java.io.*; public class FileSplitter { /*Reads IDs and Names from NamesIDs.txt file and Prints IDs in IDs.txt file and prints Names in Names.txt file */ public static void main(String args[]) throws IOException { // String variable used to read a line from the input file String line; // Opening input File "NamesIDs.txt" for reading BufferedReader fileIn = new BufferedReader(new FileReader("NamesIDs.txt")); // Opening output File "IDs.txt" for printing IDs in it PrintWriter fileOutIDs = new PrintWriter(new FileWriter("IDs.txt")); // Opening output File "Names.txt" for printing Names in it PrintWriter fileOutNames = new PrintWriter(new FileWriter("Names.txt")); line = fileIn.readLine(); // Reads the first line of the File "NamesIDs.txt" while(line != null) // Loop until the end of input file { fileOutIDs.println(line); // Prints the ID in the File "IDs.txt" line = fileIn.readLine(); // Reads the ID from the File "NamesIDs.txt" fileOutNames.println(line); // Prints the name in the File "Names.txt" line = fileIn.readLine(); // Reads the next ID from the File "NamesIDs.txt" } fileOutNames.close(); // close the output file Names.txt fileOutIDs.close(); // close the output file IDs.txt fileIn.close(); // close the input file NamesIDs.txt } } 3 Input file NamesIDs.txt: Output file IDs.txt: Output file Names.txt: Review Questions: 1. 2. 3. 4. When the loop is stopped in the above program? What will happen if the close statements are deleted? Why there are two reading statements (line = fileIn.readLine();)in the loop body? When readLine()method is used to read, what is the type of data it returns? OR When you read from the file, What is the type of the data, being read from the file? Example#4: The following example reads integers from the file, numbers.txt, and prints the sum, average and list of values below average. import java.io.*; class Average { public static void main(String[ ] args) { try { BufferedReader fin = new BufferedReader(new FileReader("numbers.txt")); String inputLine; float grade, sum = 0.0F; int count = 0; // Read lines until EOF is encountered while( ( inputLine = fin.readLine( )) != null) { grade = Float.parseFloat(inputLine); sum += grade; count++; 4 System.out.println(grade); // it displays grades on screen } // end of while if(count == 0) System.out.println("Error - no grades were read"); else System.out.println("\nThe average is " + sum / count); // it displays average on screen fin.close( ); // close input file } // end of try catch(FileNotFoundException e) { System.out.println("Error - File numbers.txt not found"); } catch(IOException e) { System.out.println("Error - An I/O error occurred"); } catch(NumberFormatException e) { System.out.println("Error - An invalid float number read"); } } // end of main method } // end of class Average Exercises Problem#1: Modify the Filesplitter.java program to do the reverse operation of that program. That is, this program will read from two files IDs.txt and Names.txt and creates the file NamesIDs.txt with IDs and Names inside. Input file IDs.txt: Input file Names.txt: 5 Output file NamesIDs.txt: Problem#2: Write a Java program which reads student grades from a text file called grades.txt and prints only the corresponding letter grades into a file called letter.txt. The letter grades are assigned according to the following table. Assume that the grades.txt file can have any number of students’ grades. Hint: The last number in the grades.txt file is -1 Score >= 90 >= 85 >= 80 >= 75 >= 65 >= 60 >= 55 >= 50 < 50 Input file: Grade A+ A B+ B C+ C D+ D F Output file: Problem#3: Cut and Past Example#4 and understand it. Now modify it so that it also prints the grades of each quiz & the average on both the screen and in the file, result2.txt. 6 Problem#4: Write a program that reads unknown number of integers from a file (number.txt), counts & writes the odd integers into a file(odd.txt) and the even integers into another file(even.txt). Print the output both on screen and in a file. Samples: Content of number.txt file: 2 8 9 11 12 0 4 Sample Output on the Screen: Content of Odd.txt file : The odd number is :9.0 The odd number is :11.0 The total odd numbers are = 2.0 Content of even.txt file: The even number is :2.0 The even number is :8.0 The even number is :12.0 The even number is :0.0 The even number is :4.0 The total even numbers are = 5.0 7