By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,720 Members | 2,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,720 IT Pros & Developers. It's quick & easy.

Checking for a FileNotFoundException in a Seperate Method

Cleo Millet
P: 7
This is just a simple program to check if a file exists or not, with the user input and the results 'File exits'/'File does not exist' all in the main method and the actual Exception catching being done in a separate method. I've got the basics of the doesFileExist method to catch any exceptions, but I can't figure out how to return that information to the main method so I can inform the user of the results.

Expand|Select|Wrap|Line Numbers
  1. import java.io.FileNotFoundException;
  2. import java.io.IOException;
  3. import java.io.RandomAccessFile;
  4. import java.util.Scanner;
  5.  
  6. public class FileApp {
  7.  
  8.     public static void main(String[] args) {
  9.  
  10.         Scanner sc = new Scanner(System.in);
  11.  
  12.         String filePath = doesFileExist(sc, "Enter the file's full path: ");
  13.  
  14.         if(!validFilePath) {
  15.             System.out.println("This File does not exist.");
  16.         }
  17.         else
  18.             System.out.println("This File exists.");
  19.  
  20.     } // End Main
  21.  
  22.  
  23.     public static String doesFileExist(Scanner sc, String prompt) {
  24.         RandomAccessFile file;
  25.         String filePath = null;
  26.         boolean validFilePath = false;
  27.  
  28.         while (!validFilePath) {
  29.             try {
  30.                 file = new RandomAccessFile(filePath, "p");
  31.                 validFilePath = true;                    
  32.             } // End Try Statement    
  33.  
  34.             catch (FileNotFoundException e) {
  35.             } // End Catch Statement 1
  36.  
  37.             catch (IOException e) {
  38.             } // End Catch Statement 2
  39.  
  40.      } // End doesFileExist Class
  41.         return filePath;
  42.  
  43. } // End Class FileApp
  44.  
  45. }
Nov 23 '11 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.