In: Computer Science
Java
Write a program that will only accept input from a file provided as the first command line argument. If no file is given or the file cannot be opened, simply print “Error opening file!” and stop executing.
A valid input file should contain two lines. The first line is any valid string, and the second line should contain a single integer.
The program should then print the single character from the string provided as the first line of input which is at the index given in the second line.
If this cannot be done for any reason, the program should simply print “Error reading input!” and stop executing.
Complete your solution to this example in Exercise.java, which is open to the left. You may use any combination of If-Then statements and Try-Catch statements to either prevent exceptions from occurring or catching them when they do occur. Either approach is valid.
Example input:
Testing123 7
Here is the correct output for that input:
1
Here’s one more input:
abcd 75
and the correct output:
Error reading input!
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFromFile { public static void main(String[] args) { if (args.length != 1) { System.out.println("Error opening file!"); return; } String fileName = args[0]; File file = new File(fileName); if (!file.exists()) { System.out.println("Error opening file!"); return; } try { Scanner fileReader = new Scanner(file); try { String line = fileReader.nextLine(); int index = fileReader.nextInt(); System.out.println(line.charAt(index)); } catch (Exception e) { System.out.println("Error reading input!"); } fileReader.close(); } catch (FileNotFoundException e) { System.out.println("Error reading input!"); } } }
==================================================================