Question

In: Computer Science

import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void...

import java.util.*;
import java.security.*;
import javax.crypto.*;
import java.nio.file.*;

public class CryptoApp {

   public static void main(String[] args) throws Exception {

Crypto crypto = new BasicCrypto();

       String welcome = "Hello 2043-er's! Let's try this again :-)";
System.out.println(welcome);

// First, where are we?
//Let's print out our current working directory
       Path cwd = FileSystems.getDefault().getPath("").toAbsolutePath();
System.out.println("Current Working Directory: " + cwd);

// Read in our file to encrypt
   byte[] originalData = Files.readAllBytes(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/encrypt.txt"));
// Encrypt it and save into a byte array
byte[] encryptedData = crypto.encrypt(originalData);
       // Decrypt it and save it into another byte array
byte[] decryptedData = crypto.decrypt(encryptedData);

// Write the encrypted text into the original file
Files.write(Paths.get(System.getProperty("user.home"), "test"), encryptedData);
// Write the decrypted text into the decrypted text file
   Files.write(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/decrypt.txt"), decryptedData);

String sendoff = "It's a wrap!";
System.out.println(sendoff);
   }
  
}

Ok so for this code I changed the name of the file from java-2022 to C-2044 to intentionally create an exception.

Exception in thread "main" java.nio.file.NoSuchFileException: /home/runner/C-2044-Sample/Crypto/src/encrypt.txt

so how would I write a try/catch/finally cause to catch one or more specific exception objects.

Solutions

Expert Solution

import java.util.*;
import java.security.*;
import javax.crypto.*;
import java.nio.file.*;

public class CryptoApp {

   public static void main(String[] args) throws Exception {

Crypto crypto = new BasicCrypto();

       String welcome = "Hello 2043-er's! Let's try this again :-)";
System.out.println(welcome);

// First, where are we?
//Let's print out our current working directory
       Path cwd = FileSystems.getDefault().getPath("").toAbsolutePath();
System.out.println("Current Working Directory: " + cwd);

// Read in our file to encrypt
   byte[] originalData = Files.readAllBytes(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/encrypt.txt"));
// Encrypt it and save into a byte array
byte[] encryptedData = crypto.encrypt(originalData);
       // Decrypt it and save it into another byte array
byte[] decryptedData = crypto.decrypt(encryptedData);

// Write the encrypted text into the original file

Files.write(Paths.get(System.getProperty("user.home"), "test"), encryptedData);
try {
        //statements in which exception could occur
// Write the decrypted text into the decrypted text file
   Files.write(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/decrypt.txt"), decryptedData);
}
catch(NoSuchFileException e)
{
        //staments to handle exception 
        //for e.g
        System.out.println(e);
}
finally {
        // code that must execute in both cases no matter whether exception occurs or not.
        String sendoff = "It's a wrap!";
        System.out.println(sendoff);

}

   }
  
}

Syntax of the try/catch/finally should be:

try{

//code in which exception might occur

}

catch(exception e)

{

//code to handle the exceptio

}

finally{

//code that must always run


Related Solutions

// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test...
// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test the smallest method System.out.print("smallest(1, 0, 2) -> "); System.out.println( smallest(1, 0, 2) ); // test the average method System.out.print("average(95, 85, 90) -> "); System.out.println( average(95, 84, 90) ); } // end main /* * smallest(double, double, double) -> double * * method is given 3 numbers, produces the smallest of the three * * examples: * smallest(1, 0, 2) -> 0.0 */ public static...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args)...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args) {             // TODO Auto-generated method stub             System.out.println("*** 1 ***");             ArrayList<Integer>list1=new ArrayList<Integer>();             for(int i=0;i<30;i++)             {                   list1.add(new Integer(i));             }             System.out.print("[");             for(int i=0;i<list1.size();i++)             {                   System.out.print(list1.get(i)+" ");             }             System.out.println("]");                           System.out.println("*** 2 ***");             ArrayList<Integer>list2=new ArrayList<Integer>();             for(int i=30;i<60;i++)             {                   list2.add(i); //Auto Boxing an Integer not need to use new Integer             }             System.out.println(list2); //toString for an ArrayList --created by the Java Programmers                           System.out.println("*** 3 ***");             ArrayList<Integer>list3=new ArrayList<Integer>();             list3.add(list1.remove(22)); //when...
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static...
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static void main(String[] args) {         PriorityQueue<Person> peopleQueue = new PriorityQueue<>();         Scanner s = new Scanner(System.in);         String firstNameIn;         String lastNameIn;         int ageIn = 0;         int count = 1;         boolean done = false;         System.out.println("Enter the first name, last name and age of 5 people.");         while(peopleQueue.size() < 5) {             System.out.println("Enter a person");             System.out.print("First Name: ");             firstNameIn...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static...
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { double num1; double num2; System.out.print("Enter two integers: "); num1 = console.nextInt(); num2 = console.nextInt(); System.out.println(); if (num1 != 0 && num2 != 0) System.out.printf("%.2f\n", Math.sqrt(Math.abs(num1 + num2 + 0.0))); else if (num1 != 0) System.out.printf("%.2f\n", Math.floor(num1 + 0.0)); else if (num2 != 0) System.out.printf("%.2f\n",Math.ceil(num2 + 0.0)); else System.out.println(0); }} a. What is the...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) {...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) { int N; Scanner keybd = new Scanner(System.in); int[] counts = new int[12];    System.out.print("Enter the number of trials: "); N = keybd.nextInt();    Random die1 = new Random(); Random die2 = new Random(); int value1, value2, sum; for(int i = 1; i <= N; i++) { value1 = die1.nextInt(6) + 1; value2 = die2.nextInt(6) + 1; sum = value1 + value2; counts[sum-1]++; }   ...
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc...
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in);    // parse the number of strings int numStrings = Integer.parseInt(sc.nextLine());    // parse each string String[] stringsArray = new String[numStrings]; for (int i = 0; i < numStrings; i++) { stringsArray[i] = sc.nextLine(); }    // print whether there are duplicates System.out.println(hasDuplicates(stringsArray)); }    private static boolean hasDuplicates(String[] stringsArray) { // TODO fill this in and remove the below line...
Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void...
Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void main(String[] args) { Rectangle r1 = new Rectangle(0,0,100,150); System.out.println(r1);    Rectangle r2 = new Rectangle(50,75,100,150); System.out.println(r2);    Rectangle r3 = r1.intersection(r2);    } } Write a program that takes both Rectangle objects, and uses the intersection method to determine if they overlap. If they do overlap, then print it's coordinates along with its width and height. If there is no intersection, then have the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT