Java - Ask user for a file name and dipslay file content. Not working I\'m tryin
ID: 3809927 • Letter: J
Question
Java - Ask user for a file name and dipslay file content. Not working
I'm trying to ask the user to enter a file name called (answers3.txt) and display the content in that file, but can't figure out what I'm doing wrong.
import java.io.IOException;
import java.util.Scanner;
public class importFile {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Enter File to dispaly: ");
String fileName = input.nextLine();
java.io.File file = new java.io.File(fileName);
Scanner input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
input.close();
}
}
Explanation / Answer
Hi, I have corrected all issue.
Please let me know in case of any issue.
import java.io.FileNotFoundException;
import java.util.Scanner;
public class importFile {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Enter File to dispaly: ");
String fileName = input.nextLine();
try{
java.io.File file = new java.io.File(fileName);
Scanner fileScanner = new Scanner(file);
while(fileScanner.hasNextLine()) {
System.out.println(fileScanner.nextLine());
}
input.close();
fileScanner.close();
}catch(FileNotFoundException e){
System.out.println("Input file is not present");
}
}
}
/*
Sample run:
Enter File to dispaly:
numbers.txt
s5
2
43
3
6
9
12
4
56
s2
10
4
8
s2
1
5
s2
4
2
10
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.