Java Programming File Exceptions Develop, Implement and test a class that reads
ID: 3812848 • Letter: J
Question
Java Programming
File Exceptions
Develop, Implement and test a class that reads an array of String from a file. The class should have a method void getStrings()
which reads from the file, and catches in order: FileNotFoundException (handled by printing “Error – file not found”), EOFException (handled by printing “Done reading file”), and IOException (handled by printing “Problem reading file” + e.getMessage()). Use a finally block to close the file.
Requirements
Design all classes.
Implement the class.
Test the complete implementation.
Submission:
The class diagram.
The Java code for class.
Your test: including test data, test cases, and test results
Explanation / Answer
ReadStrings.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class ReadStrings {
public static void main(String[] args) {
getStrings();
}
public static void getStrings() {
Scanner sc = null;
try{
sc = new Scanner(new File("D:\strings.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
String s = sc.nextLine();
lines.add(s);
System.out.println(s);
}
String[] arr = lines.toArray(new String[0]);
System.out.println(Arrays.toString(arr));
}
catch(FileNotFoundException f){
System.out.println("Error – file not found");
}
catch(IOException e){
System.out.println("Problem reading file" + e.getMessage());
}
finally {
sc.close();
}
}
}
Output:
aaaa
bbbb
cccc
dddd
eeee
[aaaa, bbbb, cccc, dddd, eeee]
strings.txt
aaaa
bbbb
cccc
dddd
eeee
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.