Write a Java program that prompts the user for a filename and attempts to open t
ID: 3543144 • Letter: W
Question
Write a Java program that prompts the user for a filename and attempts to open the file as follows:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Scanner infile = new Scanner(new FileInputStream(filename));
If there an exception thrown as a result, the program should prompt the user to reenter the
filename until a valid filename exists. (Make sure to have a textfile as part of the project to open. It
should be in the main project folder, not in any of the project subfolders.) Go to the Java API (link in
Blackboard) and look up the constructor for the FileInputStream class to determine the exceptions
that the constructor throws.
Note that your program must import both the FileInputStream class, AND the class of the exception type that the constructor of this class throws. Therefore, you must either use:
import java.io.* - to import ALL of the classes in the package
or
import java.io.FileInputStream;
import.java.io.ExceptionClassName
Explanation / Answer
import java.io.*; import java.util.*; public class PersonalityTest { public static void main(String[] args) throws FileNotFoundException { boolean isFile = false; Scanner sc = new Scanner(System.in); System.out.print("Input file name? "); String fileName = sc.next(); File inputFile = new File(fileName); while (isFile == false) { if (inputFile.exists()) { Scanner input = new Scanner(inputFile); isFile = true; } } while(input.hasNextLine()) { } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.