Question

I have written the following code that prints a list of randomly generated characters to a file, then reads them from a file, encrypts them using an exclusive or, and then prints them again. The issue is that I am receiving a FileNotFoundException even though I have placed it in a throws statement.

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException {


    //get integer mask from user input
    int mask = getMask();
    System.out.println("TEMP mask Value is: " + mask);

    //create 50 character random String and save to file
    String randomString = getRandomString(50);
    System.out.println("Original Random Character String: " + '\n' + randomString);

    //save 50 Char String from file
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Saving encrypted string...");
    System.out.print("Enter a file name: ");
    String fileName = keyboard.next();
    File outputFile = new File(fileName);
    saveFile(fileName, randomString);
    /*System.out.println("Saving Original Random Character string...");
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter a file name: ");
    String fileName = keyboard.next();
    File outputFile = new File(fileName);
    PrintWriter fileWriter = new PrintWriter(outputFile);
    fileWriter.println(randomString);

    fileWriter.close();//CLOSE OF FILEWRITER
    */


    //scan in from file
    Scanner file = new Scanner(outputFile);
    String inputString = file.nextLine();
    //print what was just scanned in from file
    System.out.print("Original random character string from the file" + 
            '\n' + inputString + '\n');

    //apply mask by convertig String to char using loop
    String maskedString = maskString(inputString, mask);
    System.out.print("Encrypted character string: " + '\n' + maskedString + '\n');
    /*String maskedString = "";
    for(int i = 0; i < inputString.length(); i++){
    char charMasked = (char)(((int) inputString.charAt(i))^mask);
    maskedString += charMasked;
    }//end of for loop
    System.out.print("Encrypted character string: " + '\n' + maskedString + '\n');
    */

    //save encrypted string
    System.out.println("Saving encrypted string...");
    System.out.print("Enter a file name: ");
    String encryptedFileName = keyboard.nextLine();
    saveFile(encryptedFileName, maskedString);





}//end of main method
/**
 * Preconditions: must call randomString method to get random 
 * characters
 * Postconditions: user will have a string of random characters of desired
 * length
 * @param count allows user to choose how many random characters to return
 */
public static String getRandomString(int count)throws FileNotFoundException{

    String listChars = "";
    for (int i = 0; i < count; i++) {
        char randomChar = (char) ((Math.random() * 255) + 32);/////////////////////getting less than 50 characters sometimes, possible control characters?
        listChars += randomChar;
    }//end of for loop
    return listChars;
}//end of randomString method

/**
 * Precondition: must call getMask method to get prompt user to enter the 
 * encryption mask that will be used to encrypt the file input
 * Postcondition: user has entered an integer string that will be used to 
 * encrypt the 50 char random String we will read from a file
 * @return output, which is the user entered integer value
 */

public static int getMask(){
    //Prompt user to enter integer mask
    System.out.print("Enter the encryption mask: ");
    Scanner keyboard = new Scanner(System.in);
    int output = keyboard.nextInt();
    return output;
}//end of getMask method

public static void saveFile(String fileName, String toBePrinted)throws FileNotFoundException{

    File outputFile = new File(fileName);
    PrintWriter fileWriter = new PrintWriter(outputFile);
    fileWriter.println(toBePrinted);

    fileWriter.close();//CLOSE OF FILEWRITER
}//end of saveFile method

public static String maskString(String inputString, int mask){
String maskedString = "";
    for(int i = 0; i < inputString.length(); i++){
    char charMasked = (char)(((int) inputString.charAt(i))^mask);
    maskedString += charMasked;
    }//end of for loop
    return maskedString;
}//end of maskString method

Upon execution of my code I receive something along the lines of Exception in thread "main" java.io.FileNotFoundException: (No such file or directory). I thought this error would be prevented by my use of the throws FileNotFoundException statement.

I have reviewed the Oracle Java Tutorial here

I am honestly trying but it is just not clicking with me. I have only ever used a try-catch statement to catch exceptions like this. Is that what I need to do here every single time I try and save a file which is not previously created?

Was it helpful?

Solution

throws clause in the method signature only means that "I am aware that this method can throw this exception and I do NOT catch it here, so the caller should catch it."

In your example you are just tricking your compiler so that it won't complain about uncaught exception.

OTHER TIPS

By adding the FileNotFoundException you are stating the function may throw this exception, but you are not adding anything that will catch and suppress the Exception.

I would wrap your code into a function/class, then in your main code block add a try block that calls your function/class, and add a catch block for the FileNotFoundException.

The throws clause doesn't avoid the exception from being thrown. Actually, it just declares the method as throwing such exception so that other methods calling it can treat it accordingly.

If you want to suppress exceptions, you must surround your statement with a try-catch statement. However, suppressing exceptions is not a good practice. You should instead treat them correctly and show a compatible message to your user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top