FileNotFoundException not being thrown - java

I am writing a piece of code that returns a scanner for a user-input file name. Here's the code:
public static Scanner getInputScanner(Scanner console) {
System.out.print("Enter input file: ");
String fileName = "";
try {
fileName = console.nextLine();
File f = new File(fileName);
} catch (FileNotFoundException e) {
while (!(new File(fileName)).exists()) {
System.out.println(fileName + " (No such file or directory)");
System.out.print("Enter input file: ");
fileName = console.nextLine();
}
}
File f = new File(fileName);
return new Scanner(f);
}
I am getting two errors:
Compression.java:49: error: exception FileNotFoundException is never thrown in body of corresponding try statement
} catch (FileNotFoundException e) {
^
Compression.java:57: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
return new Scanner(f);
I can't figure out why the try block isn't throwing an exception, since the user could input an invalid file name.
Thanks for any help.
EDIT: changed the FileNotFoundException to a NullPointerException and that fixed the first problem. Now, however, I get an error that my return statement is throwing an unreported FileNotFoundException. But this code wouldn't execute unless the file is valid, right? Is Java blind to this, and requires I catch the exception anyway?

The FileNotFoundException is neither thrown by Scanner#nextLine() nor by creating a new File object (File#new(String)). Both functions do nothing that is related to file I/O.
Scanner.nextLine() operates on an alread existing input source
File#new() creates simply a new File object that points (file name) to an (maybe existing) actual file.
The creation of a new Scanner object in contrast, involves creating a new InputStream, so it actually touches the supplied file by opening it.
From java.util.Scanner:
public Scanner(File source) throws FileNotFoundException {
this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}

The documentation clearly states that the File(String pathname) constructor can only throw NullPointerException and NOT FileNotFoundException.
If you want to see if the file name is valid, use f.exists().

return new Scanner(f);
throws error when file is not found, it can't return the scanner(f) . so should be wrapped in try-catch block.
or you need to make the getInputScanner to throw the FileNotFoundException

File f = new File(fileName);
does not throw an exception if the file does not exist. A File object is really just a filename; it does not refer to the actual file. If the file does not exist, you will get an exception when you try to use it.
new Scanner(f) is the part that throws a FileNotFoundException.

You can always call File.exists() before you construct your Scanner and if you use an infinite loop you can simplify your logic and eliminate those errors. Something like,
public static Scanner getInputScanner(Scanner console) {
while (true) {
System.out.print("Enter input file: ");
String fileName = console.nextLine();
File f = new File(fileName);
if (!f.exists()) {
System.out.println(fileName + " (No such file or directory)");
continue;
}
try {
return new Scanner(f);
} catch (FileNotFoundException e) {
// This shouldn't happen.
e.printStackTrace();
System.out.println(fileName + " (No such file or directory)");
}
}
}

Related

How can I let user input the name of text file again if the name of file already exists?

public static void textFileOpen(String fileName) throws IOException
{
while(true)
{
try
{
FileReader fileReader = new FileReader(fileName);
LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
BufferedReader bufferedReader = new BufferedReader(fileReader);
fileReader.close();
bufferedReader.close();
lineNumberReader.close();
}
catch(Exception ex)
{
System.out.println("File " + fileName + " does not exists! Please try again.");
}
}
}
I'm trying to let the user input file name again if exists. But it runs forever if user enter an exist file name. How can I fix it? Can anyone help, please? THank you
The cause is your use of try(input). As the scanner has already been closed after the first catch , it is not able to take any new input.
Remove the (input) and use a separate input.close should work.
You shouldn't close a Scanner that wraps System.in since System.in represents the standard input which is generally the computer keyboard. So when you close it, your program cannot receive input from the keyboard.
You should also not use exception handling to test a condition. You should use a conditional statement, like an if statement.
In order to test whether a file exists, you can call method isFile. The method returns...
true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise
When you create a FileWriter, it also creates the file if it doesn't already exist.
Here is code demonstrating the above.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Cipher {
public static void main(String[] args) throws IOException {
System.out.println("Enter fileName: ");
Scanner input = new Scanner(System.in);
String fileName = null;
File file = null;
while (true) {
fileName = input.nextLine();
file = new File(fileName);
if (file.isFile()) {
System.out.println(file + " already exists! Please try again:");
}
else {
break;
}
}
FileWriter writer = new FileWriter(file);
}
}

Try/Catch For File Not Found Exception Nested inside a While Loop

I'm trying to code for a file not found exception in a while loop so that the program continues prompting the user for the file (test.txt). I wrote a try/catch block inside a while loop. However, when I delete the input file (test.txt), the program should catch this error and print "Error, cannot locate the 'test.txt' file, please try again:" and allow the user to input another file name. However, the program crashes and gives me a FileNotFoundException.
In this case it's probably better to ask for permission rather than forgiveness (e.g. check if the file exists before attempting to read it).
File file = new File("test_input.txt");
if (file.exists()) {
FileReader fileReader = new FileReader(file);
}
You should add another try and catch for the Scanner
// prompt user for name for output textfile
System.out.println();
System.out.print("What would you like to call your output file: ");
String outputName = inputReader.nextLine();
// scanner and printwriter objects for reading text file
try {
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
// messages triggered by successful location of files.
if (fileName.equalsIgnoreCase(("test_input.txt"))) {
// code logic
}
} catch (FileNotFoundException ex) {
System.out.println();
System.out.println("***** ERROR *****");
System.out.println("\nCannot locate the input file " + "'" + fileName + "'" + "on your computer - please try again.");
System.out.print("\nInput file name (from your computer): ");
}
In your code, two lines raise FileNotFoundExceptions that you are not catching:
// scanner and printwriter objects for reading text file
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
You can replace them with the following, and the code (should) work.
Scanner in = null;// Initialize to null, so they don't raise warnings.
PrintWriter out = null;
try { // Surround with try/catch to get the exception
in = new Scanner(correctInputfile);
out = new PrintWriter(outputName);
}catch(FileNotFoundException e){
/*TODO: something about the exception here!
Make sure the Scanner and PrintWriter get
properly initialized with valid file names.*/
}

How to use try/catch to avoid throwing FileNotFoundException in java

I am trying to output a file scanner object from my method. This is a school assignment and I am specifically instructed to NOT throw any exceptions, but use try/catch instead. The assignment requires that the command line prompt the user for a file to scan. If the file does not exist, we are supposed to tell the user, then prompt them for a file again. If the file does exist, then the method returns a scanner object that scans the file.
My code works, but it is not clean. It involves 2 methods. This is my code so far:
public static Scanner getInputScanner (Scanner console) {
File inputFile = null;
Scanner input = null;
try {
inputFile = getFile(inputFile, console);
input = new Scanner (inputFile);
return input;
} catch (FileNotFoundException e) {
try {
return input = new Scanner (getFile (inputFile, console));
} catch (FileNotFoundException f) {
System.out.println("An error has occured.");
return input;
}
}
}
public static File getFile (File inputFile, Scanner console) {
System.out.println("Enter input file: ");
inputFile = new File (console.nextLine());
while (!inputFile.exists()) {
System.out.println("File does not exist.");
System.out.print("Enter input file: ");
inputFile = new File (console.nextLine());
}
return inputFile;
}
The problem with the code is that the output looks like this:
Enter input file:
File does not exist.
Enter input file:
It then is waiting for the user's input. I don't want the output to have the 2 lines of code before the last line though.
Can anybody explain why my code is outputting these 2 lines?
Also, is there a simpler solution to getting an input file without throwing the FileNotFoundException?
Thanks!
If I understand correctly,
your program outputs these lines when you run it,
no matter what,
without you getting a chance to actually enter a filename.
Enter input file:
File does not exist.
And then the programs asks you again:
Enter input file:
And you don't want the first two lines above, right?
This can happen for example if the Scanner console you received has an unread newline in it.
You haven't posted that part of the code,
so it's hard to tell, but this is a common gotcha with Scanner.
Before calling getInputScanner,
make sure the Scanner console is ready to use,
with no unread garbage still buffered in it.
As for the second part of your question,
yes this can be written simpler and better, for example:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}
It execute below line as soon the getFile() being called.
System.out.print("Enter input file: ");
Since no file exist, the below lines keeps on executing :
while (!inputFile.exists()) {
System.out.println ("File does not exist.");
System.out.print("Enter input file: ");
You can use throws() instead of try/catch, then caller will take care of exception.
Had to consume whatever junk was being carried over from the scanner by inserting a Scanner.nextLine() before getting user input. Final code looks like this:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
console.nextLine();
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}

Invalid file destination in Java?

Scanner user = new Scanner(System.in);
String word;
System.out.println("Location of file: ");
word = user.nextLine();
FileReader fileOpen = new FileReader(word);
BufferedReader fileRead = new BufferedReader(fileOpen);
How can I do an error check if the user enters a wrong file destination?
I get:
java.io.FileNotFoundException:
when a invalid file destination is entered.
I want the program to say something like
System.out.println("Invalid directory");
I get errors for the methods isDirectory() and exists() telling me they don't exist for the type String when I try:
if (word.exists())
{
//do blah blah
}
else
{
//Print error
}
Wrap your word in File and then do the checks:
if (new File(word).exists())
{
//do blah blah
}
else
{
//Print error
}
Alternatively, you may catch an exception when it is thrown:
Scanner user = new Scanner(System.in);
String word;
System.out.println("Location of file: ");
word = user.nextLine();
try {
FileReader fileOpen = new FileReader(word);
BufferedReader fileRead = new BufferedReader(fileOpen);
} catch (FileNotFoundException fnf) {
// print an error
}
Create a File instance of 'word' then check if it exists. For the exception, surround it with a try and catch, in the catch: put the code you want to run should it not exist.

Why is it that we don't need to use try-catch block when reading data but we do need try-catch when attaching a Scanner to a file?

Im reading a programming book on The Scanner, and it's saying that we don't need to use try-catch block when reading data because IOException are captured, but we do need try-catch when attaching a Scanner to a file.
for example, in the following code the try-catch is needed. Can you show me an example where try-catch isn't needed but the error is captured by IOException?
Scanner scnaFile = null;
String fileName = "dataFile.txt";
try{
scanFile = new Scanner(new File(fileName));
} catch (FileNotFoundException ex){
System.err.println(filename + " not found");
System.exit(1);
}
Can you show me an example where try-catch isn't needed but the error
is captured by IOException?
Example:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
These nextXXXmethods will not thrown any exception related to I/O as this is captured in the code.
They will throw an exception though if the input is exausted.
Read the Scanner Javadoc

Categories

Resources