I got this question where I got to write a class named DecryptMessage that reads a secret message stored in a file called Mymessage.txt and decrypt the message. I really have no idea how to start. Please anybody help me? Much appreciated.
Below is what I've done and more or less I manage to got the answer thanks to whoever have helped and just to share the answers.
package decryptmessage;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.*;
public class DecryptMessage {
public static void main(String[] args)
{
int key = 10;
FileWriter fWriter = null;
BufferedWriter writer = null;
try
{
File file = new File("C:\\Users\\Desktop\\Decrypted.txt");
fWriter = new FileWriter(file.getAbsoluteFile());
writer = new BufferedWriter(fWriter);
//if file not exist, create a new file. If exist, delete the file and create a new file
if (!file.exists())
{
file.delete();
file.createNewFile();
}
else
{
file.createNewFile();
}
}
catch(Exception e)
{
System.out.println("Unable to create file");
}
try
{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Desktop\\Mymessage.txt"));
String line = "";
while ((line = br.readLine()) != null)
{
writer.write(decrypt(line,key));
writer.newLine();
}
if(br.readLine() == null)
{
writer.close();
}
}
catch(Exception e)
{
System.out.println("Unable to write into file");
}
}
private static String decrypt(String s, int key)
{
String decrypt = "";
for(int i = 0; i < s.length(); i++ )
{
decrypt +=(char) (s.charAt(i) + key);
}
return decrypt;
}
}
I suggest you to first learn how to
read and write
onto files from here.Then, take your text and
encrypt
it with akey
. When you're reading itdecrypt
it with the same key.Here's a small example on how to encryt and decrypt
EDIT
}