jasonpogi1669

Simple Encryption (using Java) Technical Assessment 3

Mar 2nd, 2021 (edited)
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Task2{
  5.   public static void main(String[] args) {
  6.    
  7.     // Read from file
  8.     Scanner in = new Scanner(System.in);
  9.     String data = "";
  10.     int shift_size = 0;
  11.     System.out.print("Enter file name (for input): ");
  12.     String file_name = in.next();
  13.     try {
  14.         System.out.print("Shift size: ");
  15.         shift_size = in.nextInt();
  16.         File file_object = new File(file_name + ".txt");
  17.         Scanner scanner_object = new Scanner(file_object);
  18.         System.out.print("Message read from the file: ");
  19.         while (scanner_object.hasNextLine()) {
  20.             data += scanner_object.nextLine();
  21.         }
  22.         scanner_object.close();
  23.         System.out.println(data);
  24.     } catch (FileNotFoundException e) {
  25.         System.out.println("An error occurred.");
  26.         e.printStackTrace();
  27.     }
  28.  
  29.     // Create file
  30.     System.out.print("Enter file name (for output): ");
  31.     file_name = in.next();
  32.     try {
  33.         File file_object = new File(file_name + ".txt");
  34.         if (file_object.createNewFile()) {
  35.             System.out.println("File created: " + file_name + ".txt");
  36.         } else {
  37.             System.out.println("File already exists.");
  38.         }
  39.     } catch (IOException e) {
  40.         System.out.println("An error occurred.");
  41.         e.printStackTrace();
  42.     }
  43.  
  44.     // Write encrypted message to file
  45.     try {
  46.         FileWriter file_writer_object = new FileWriter(file_name + ".txt");
  47.         StringBuilder new_string = new StringBuilder(data);
  48.         for (int i = 0; i < (int) data.length(); i++) {
  49.             if (new_string.charAt(i) != ' ') {
  50.                 new_string.setCharAt(i, (char) (new_string.charAt(i) + shift_size));
  51.             }
  52.         }
  53.         System.out.print("Encrypted message: ");
  54.         System.out.println(new_string);
  55.         file_writer_object.write(new_string.toString());
  56.         file_writer_object.close();
  57.         System.out.println("Successfully encrypted!");
  58.     } catch (IOException e) {
  59.         System.out.println("An error occurred.");
  60.         e.printStackTrace();
  61.     }
  62.    
  63.   }
  64. }
Add Comment
Please, Sign In to add comment