In: Computer Science
Needs to be in basic JAVA
Write a program that does basic encrypting of text. You will ask the user the filename of a text file that contains a few sentences of text. You will read this text file one character at a time, and change each letter to another one and write out to an output file. The conversion should be done a -> b, b->c , … z->a, A->B, B->C, …. Z->A. This means just shift each letter by one, but Z goes back to A.
Example: Hello converts to Ifmmp
All other punctuation and spaces or symbols can stay as they are.
If you have time you could write the reverse program that would take your encrypted file as the input and get back the original message
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EncryptDecrypt
{
public static void encrypt(String inFile, String
outFile) throws IOException {
File f=new File(inFile); //Creation
of File Descriptor for input file
FileReader fr=new FileReader(f); //Creation of File
Reader object
//creating file writer object
FileWriter fw = new FileWriter(new
File(outFile));
BufferedReader br=new BufferedReader(fr); //Creation
of BufferedReader object
int c = 0;
while((c = br.read()) != -1) //Read char by Char
{
//shifting by 1
int ch =
c;
//checkking if
upper case or lower case and converting accordingly
if(Character.isUpperCase(ch)) {
ch = ((c+1)-65 ) % 26 + 65;
} else
if(Character.isLowerCase(ch)) {
ch = ((c+1)-97 ) % 26 + 97;
}
char character = (char) ch; //converting integer to
char
//qriting to output file
fw.append(character);
}
br.close();
fw.close();
}
public static void decrypt(String file) throws
IOException {
File f=new File(file); //Creation
of File Descriptor for input file
FileReader fr=new FileReader(f); //Creation of File
Reader object
BufferedReader br=new BufferedReader(fr); //Creation
of BufferedReader object
int c = 0;
while((c = br.read()) != -1) //Read char by Char
{
//shifting by 1
int ch = c;
if(Character.isUpperCase(ch)) {
ch = ((c-1)-65 ) % 26 + 65;
} else
if(Character.isLowerCase(ch)) {
ch = ((c-1)-97 ) % 26 + 97;
}
char character = (char) ch; //converting integer to
char
System.out.print(character);
}
br.close();
}
public static void main(String[] args) throws IOException
{
encrypt("D://input.txt", "D://output.txt");
decrypt("D://output.txt");
}
}