Question

[Java] Create a class called FileExercises that contains the following method Method encrypt that does not...

[Java] Create a class called FileExercises that contains the following method

  • Method encrypt that does not return anything and takes a shift, input filename and output filename as arguments. It should read the input file as a text file and encrypt the content using a Caesar cypher with the shift provided. The resulting text should be placed in the output file specified. (If the output file already exists, replace the existing file with a new file that contains the required content.) You can find a description of the Caesar cypher on-line. If a character in the file is not alphabetic, leave the character unchanged. Convert upper case character to upper case characters and lower case characters to lower case characters.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileExercises {

   // function to encrypt input file and store the result in output


   public static void encrypt(int shift, String inputFileName, String outputFileName) {

       try {
           File inputFile = new File(inputFileName); // input file object
           File outputFile = new File(outputFileName); // output file object
           FileReader fileReader = new FileReader(inputFile);
           FileWriter fileWriter = new FileWriter(outputFile);
           BufferedReader bufferedReader = new BufferedReader(fileReader);
           BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
           String line;
           while ((line = bufferedReader.readLine()) != null) { // read file line by line
               bufferedWriter.write(encryptHelper(line, shift).toString()); // encrypt line by line and write to output
                                                                               // file
               bufferedWriter.write("\n");
           }
           fileReader.close();
           bufferedWriter.close();
           fileWriter.close();
           System.out.println("File encrypted successfully");

       } catch (IOException e) {
           e.printStackTrace();
       }

   }

   // helper function to encrypt text
   public static StringBuffer encryptHelper(String text, int shift) {
       StringBuffer result = new StringBuffer();

       for (int j = 0; j < text.length(); j++) {
           if (Character.isAlphabetic(text.charAt(j))) { // check if current character is alphabet
               if (Character.isUpperCase(text.charAt(j))) {
                   char character = (char) (((int) text.charAt(j) + shift - 65) % 26 + 65); // shift character by shift
                                                                                               // times
                   result.append(character);
               } else {
                   char character = (char) (((int) text.charAt(j) + shift - 97) % 26 + 97); // shift character by shift
                                                                                               // times
                   result.append(character);
               }
           } else {
               result.append(text.charAt(j)); // if not alphabet add character as it is
           }
       }
       return result;
   }

   public static void main(String... args) {
       String inputFileName, outputFileName;
       int shift;
       Scanner scan = new Scanner(System.in);
       System.out.println("Enter input file name");
       inputFileName = scan.nextLine(); // ask for input file name
       System.out.println("Enter output file name");
       outputFileName = scan.nextLine(); // ask for output file name
       System.out.println("Enter shift for caesar cipher");
       shift = scan.nextInt(); // ask for shift

       encrypt(shift, inputFileName, outputFileName); // call encrypt function

   }

}
//output

Add a comment
Know the answer?
Add Answer to:
[Java] Create a class called FileExercises that contains the following method Method encrypt that does not...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • create a Java class ShiftCipher The program ShiftCipher should take two inputs from the terminal. The...

    create a Java class ShiftCipher The program ShiftCipher should take two inputs from the terminal. The first should be a string of any length which contains any type of symbol (the plaintext). The second will be a shift value which should be between 0 and 25 inclusive (though you may design your program to be resilient to shifts beyond this value). The program should print the cipher text, in which each of the alphabetic characters in the string is shifted...

  • JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information...

    JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information being exposed, it is becoming more and more important to find ways to protect our sensitive data. In this program we will develop a simple tool that helps users generate strong passwords, encrypt and decrypt data using some cyphering techniques. You will need to create two classes. The first class is your driver for the application and contains the main method. Name this class...

  • Kindly follow the instructions provided carefully. C programming   Project 6, Program Design One way to encrypt...

    Kindly follow the instructions provided carefully. C programming   Project 6, Program Design One way to encrypt a message is to use a date’s 6 digits to shift the letters. For example, if a date is picked as December 18, 1946, then the 6 digits are 121846. Assume the dates are in the 20th century. To encrypt a message, you will shift each letter of the message by the number of spaces indicated by the corresponding digit. For example, to encrypt...

  • USING JAVA Consider the following methods: StringBuilder has a method append(). If we run: StringBuilder s...

    USING JAVA Consider the following methods: StringBuilder has a method append(). If we run: StringBuilder s = new StringBuilder(); s.append("abc"); The text in the StringBuilder is now "abc" Character has static methods toUpperCase() and to LowerCase(), which convert characters to upper or lower case. If we run Character x = Character.toUpperCase('c');, x is 'C'. Character also has a static isAlphabetic() method, which returns true if a character is an alphabetic character, otherwise returns false. You will also need String's charAt()...

  • C Program In this assignment you'll write a program that encrypts the alphabetic letters in a...

    C Program In this assignment you'll write a program that encrypts the alphabetic letters in a file using the Vigenère cipher. Your program will take two command line parameters containing the names of the file storing the encryption key and the file to be encrypted. The program must generate output to the console (terminal) screen as specified below. Command Line Parameters Your program must compile and run from the command line. The program executable must be named “vigenere” (all lower...

  • You will be writing a simple Java program that implements an ancient form of encryption known...

    You will be writing a simple Java program that implements an ancient form of encryption known as a substitution cipher or a Caesar cipher (after Julius Caesar, who reportedly used it to send messages to his armies) or a shift cipher. In a Caesar cipher, the letters in a message are replaced by the letters of a "shifted" alphabet. So for example if we had a shift of 3 we might have the following replacements: Original alphabet: A B C...

  • python

    Complete the below function that takes a file name and a list as arguments and reads the text within the corresponding file, then creates a dictionary whose keys are the characters of the provided list, and the values are the counts of these characters within the text. If a character in the list is not included in  the text, "0" should be written in the dictionary as the value of this  character. The function returns the created dictionary as a result. If the file  does not exist, then the function returns an empty dictionary. Here is an example case, assuming a file named "sample.txt" exists with the  following content: ----- sample.txt ----- This is an example sentence. This is yet another sentence. ------------------------- >>> text2dict("sample.txt", ['a', 'b', 'c', 't']) {'a':3, 'b':0, 'c':2, 't':4} """ def text2dict(filename, characters):     return # Remove this line to answer this question

  • Create a class called DuplicateRemover. Create an instance method called remove that takes a single parameter...

    Create a class called DuplicateRemover. Create an instance method called remove that takes a single parameter called dataFile (representing the path to a text file) and uses a Set of Strings to eliminate duplicate words from dataFile. The unique words should be stored in an instance variable called uniqueWords. Create an instance method called write that takes a single parameter called outputFile (representing the path to a text file) and writes the words contained in uniqueWords to the file pointed...

  • java find and replace code pls help me We write code that can find and replace...

    java find and replace code pls help me We write code that can find and replace in a given text file. The code you write should take the parameters as command line arguments: java FindReplace -i <input file> -f "<find-string>" -r "<replace-string> -o <output file> *question mark(?) can be used instead of any character. "?al" string an be sal ,kal,val *In addition, a certain set of characters can be given in brackets.( "kng[a,b,f,d,s]ne" string an be kngane,hngbne,kangfne,kangdne,kangsne So, all you...

  • Write a function called char_counter that counts the number of a certain character in a text file. The function takes tw...

    Write a function called char_counter that counts the number of a certain character in a text file. The function takes two input arguments, fname, a char vector of the filename and character, the char it counts in the file. The function returns charnum, the number of characters found. If the file is not found or character is not a valid char, the function return -1. As an example, consider the following run. The file "simple.txt" contains a single line: "This...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT