Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by MOHIT on 07-11-2016.
- */
- import java.io.File;
- import java.io.IOException;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.util.ArrayList;
- import java.util.Scanner;
- import java.util.Random;
- import java.io.FileWriter;
- public class caesarCipher {
- public static void main(String arg[]){
- Scanner sc = new Scanner(System.in);
- //System.out.print("Enter the String to be encrypted : ");
- //String inString = sc.nextLine();
- System.out.print("\nEnter the Shift value : ");
- int shift_value = sc.nextInt();
- // String finalString = encrypt_(inString,cipher);
- encrypt_file(shift_value);
- // System.out.print("\nThe encrypted String is : " + finalString);
- }
- static String encrypt(String original_msg, int shift_value){
- String allChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
- int all_chars_length = allChars.length();
- String encrypted_msg = "";
- for(int i=0; i< original_msg.length(); i++){
- Character letter = original_msg.charAt(i);
- if(allChars.indexOf(letter) >= 0) {
- int position = allChars.indexOf(letter);
- position += shift_value;
- position %= all_chars_length;
- Character e_letter = allChars.charAt(position);
- encrypted_msg += e_letter;
- }else{
- encrypted_msg += letter;
- }
- }
- return encrypted_msg;
- }
- static void encrypt_file(int shift_value){
- FileInputStream fin;
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter the path of the file : ");
- String file_name = sc.nextLine();
- String fullFile = "";
- try {
- fin = new FileInputStream(file_name);
- Scanner fp = new Scanner(fin);
- int size = 0;
- while (fp.hasNextLine()) {
- String line = fp.nextLine();
- fullFile += line + "\n";
- size += line.length();
- }
- System.out.println("File read successfully!!");
- fullFile = encrypt(fullFile, shift_value);
- System.out.println("Data encrypted successfully!!");
- System.out.println(fullFile);
- }catch (Exception e){
- e.printStackTrace();
- }
- try {
- File newTextFile = new File("C:\\Users\\MOHIT\\Desktop\\encrypted_file.txt");
- FileWriter f1 = new FileWriter(newTextFile);
- f1.write(fullFile);
- f1.close();
- System.out.println("Encrypted file stored on Desktop");
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- }
- /*
- Output for encrypting a file
- Enter File name :F:/python_3.4/sample.txt
- Enter File name : F:/python_3.4/sample.txt
- File read successufully!!
- File data encrypted successfully!!
- Encrypted file stored on Desktop!!
- */
Add Comment
Please, Sign In to add comment