You are on page 1of 3

import java.io.

*;
class CaesarCipher
{
static int m;
static int key;
static String s2="";
static String s="";
public static void main(String a[]) throws java.io.IOException
{
int i,j,y=0;
String source_file=a[1];
String Intermediate_file=a[2];
String destination_file=a[3];
char choice,ans='y';
key=Integer.parseInt(a[0]);
char alpha1[]=new char[26];
char alpha[]=new char[26];
for(int k=97;k<123;k++,y++)
{
alpha1[y]=(char)k;
}
y=0;
for(int k=65;k<91;k++,y++)
{
alpha[y]=(char)k;
}
System.out.println("Enter your choice:");
choice=(char)System.in.read();
switch(choice)
{
//Case 1 is for enciphering process
case '1':
File f1=new File(source_file);
FileReader f=new FileReader(f1);
while(( i=f.read())!=-1)
{
if(i>=97&&i<=122)
{
for( j=0;j<26;j++)
{
if(alpha1[j]==((char)i))
{
m=j;
break;
}
}
s2+=alpha1[((m+key)%26)];
}
else if (i>=65&&i<91)
{
for( j=0;j<26;j++)
{
if(alpha[j]==((char)i))
{
m=j;
break;
}

}
s2+=alpha[((m+key)%26)];
}
else
s2+=" ";
}
f.close();
char buf[]=s2.toCharArray();
FileWriter fw=new FileWriter(Intermediate_file);
fw.write(buf);
fw.close();
break;
//Case2 is for deciphering process
case '2':
FileReader f2=new FileReader(Intermediate_file);
while(( i=f2.read())!=-1)
{
if(i>=97&&i<=123)
{
for( j=0;j<26;j++)
{
if(alpha1[j]==((char)i))
{
m=j;
break;
}
}
if(m>=key)
s+=alpha1[((m-key)%26)];
else
s+=alpha1[((26+m-key)%26)];
}
else if(i>=65&&i<=90)
{
for( j=0;j<26;j++)
{
if(alpha[j]==((char)i))
{
m=j;
break;
}
}
if(m>=key)
s+=alpha[((m-key)%26)];
else
s+=alpha[((26+m-key)%26)];
}
else
s+=" ";
}
f2.close();
char buf1[]=s.toCharArray();
FileWriter fw1=new FileWriter(destination_file);
fw1.write(buf1);
fw1.close();
break;
default:
System.out.println("Your choice is invalid:");
}
}

You might also like