Write a program that allows users to encrypt and decrypt files. The file encrypt
ID: 3624859 • Letter: W
Question
Write a program that allows users to encrypt and decrypt files. The file encryption technique we willuse for this program is the highly secure “one letter off” system. So an “a” will be represented by a
“b”, and a “b” will be represented by a “c” in the encrypted file. (For simplicity’s sake, only
alphabetical characters will be encrypted. Punctuation and other symbols will be left intact.)
Prompt the user as to whether they would like to encrypt or decrypt the file. Then prompt the user for
the file name, and perform the encryption or decryption. Output the file to a new file named
“Encrypted.txt” or “Decrypted.txt”, depending on what the user has selected to do.
HINT: Using an ArrayList to store the letters of the alphabet may simplify both encrypting and
decrypting the file. In addition, using some of the other tools that we have picked up this semester
may also help, such as:
- Using multiple methods in a program
- For loops, and the String “charAt()” method
- The Character class, with methods like “isLetter()”
- ArrayList methods like “indexOf()”
Explanation / Answer
import java.util.*;
import java.io.*;
public class EncryptORDecrypt {
public static void main(String[] args) throws Exception {
DataInputStream input=new DataInputStream(System.in);
System.out.print("1.Encrypt a file 2.Decrypt a file ");
System.out.print("Enter your coice: ");
int n=Integer.parseInt(input.readLine());
System.out.print("Enter file name with out extension: ");
String file=input.readLine();
switch(n)
{
case 1:
encrypt(file);
break;
case 2:
decrypt(file);
break;
default:
System.out.println("Invalid choice");
}
}
public static void encrypt(String file) throws Exception
{
BufferedReader br=new BufferedReader(new FileReader(file+".txt"));
PrintWriter ps=new PrintWriter(new FileOutputStream("Encrypt.txt"));
String line;
while((line=br.readLine())!=null)
{
for(int i=0;i<line.length();i++)
{
Character c=line.charAt(i);
char ch=line.charAt(i);
if(c.isLetter(ch))
{
if(ch=='z')
ch='a';
else if(ch=='Z')
ch='A';
else
ch++;
}
ps.write(""+ch);
}
}
br.close();
ps.close();
System.out.println("file encrypted successfully check the Encrypt.txt file");
}
public static void decrypt(String file) throws Exception
{
BufferedReader br=new BufferedReader(new FileReader(file+".txt"));
PrintWriter ps=new PrintWriter(new FileOutputStream("Decrypt.txt"));
String line;
while((line=br.readLine())!=null)
{
for(int i=0;i<line.length();i++)
{
Character c=line.charAt(i);
char ch=line.charAt(i);
if(c.isLetter(ch))
{
if(ch=='a')
ch='z';
else if(ch=='A')
ch='Z';
else
ch--;
}
ps.write(""+ch);
}
}
br.close();
ps.close();
System.out.println("file decrypted successfully check the Decrypt.txt file");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.