0

I'm trying to pass in a text file(input and output files) as the command line arguments inside a try-catch block.

This is a snippet of the code:

try {
    PrintWriter outFile = new PrintWriter(new FileOutputStream(args[0]));
} catch (FileNotFoundException exc) {
    System.out.println("file does not exist");
} catch (Exception e) {
    System.out.println("general exception");
}

I'm trying to check it by passing a file that doesn't exist but it doesn't seem to work, not even in the general exception. I tried printStream as well but nothing really changed.

Any help would be appreciated, thanks!

1
  • According to the FileOutputStream JavaDoc, FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason. Perhaps the file you are passing in CAN be created, so it is creating it for you. Maybe make the directory read only and see if it still works. Commented Sep 19, 2016 at 16:19

1 Answer 1

1

First create a file from text

   File inputFile = new File(args[0]);

Now check the existence of file using inputFile.exists() which will give you boolean result true if file exists or false if doesn't

Plus you also wanna put a check for directories too because inputFile.exists() also return true if the input Path is of a directory (Folder)

so your check will look like

if(inputFile.exists() && ! inputFile.isDirectory()) // ! mean not/complement operator 
 { 
     // yes it's a file
 }

Why complement ? cuz we wanna only go further if input represents a file not directory

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.