Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Iterator;
- public class Main {
- public static void main(String[] args)
- {
- ArrayList<String> msg=readFromFile("plaintext.txt");
- writeToFile(msg,"cipherText.txt");
- ArrayList<String> normalText=readFromFile("cipherText.txt");
- writeToFile(normalText,"plaintext2.txt");
- }
- public static ArrayList<String> readFromFile(String path)
- {
- BufferedReader br = null;
- //ArrayList[] msg = null;
- ArrayList<String> msg = new ArrayList<String>();
- try {
- String sCurrentLine;
- br = new BufferedReader(new FileReader(path));
- int i=0;
- while ((sCurrentLine = br.readLine()) != null)
- {
- if(path=="plaintext.txt")
- {
- String result=encode(sCurrentLine,3);
- msg.add(result);
- }
- else
- {
- String originalLine=decode(sCurrentLine);
- msg.add(originalLine);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (br != null)br.close();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return msg;
- }
- public static void writeToFile(ArrayList<String> msg,String path)
- {
- try {
- File file = new File(path);
- // if file doesnt exists, then create it
- if (!file.exists()) {
- file.createNewFile();
- }
- FileWriter fw = new FileWriter(file.getAbsoluteFile());
- BufferedWriter bw = new BufferedWriter(fw);
- Iterator<String> iterator = msg.iterator();
- while (iterator.hasNext())
- {
- //System.out.println(iterator.next());
- bw.write(iterator.next());
- bw.newLine();
- }
- bw.close();
- System.out.println("Done");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static String encode(String line,int key)
- {
- char[] lineChar=line.toCharArray();
- int offset=key%26+26;
- StringBuilder secretMessage=new StringBuilder();
- for(int i=0;i<lineChar.length;i++)
- {
- if(lineChar[i]==' ')
- {
- secretMessage.append(lineChar[i]);
- continue;
- }
- else
- {
- secretMessage.append((char) ('A' + (lineChar[i] - 'A' + offset) % 26 ));
- }
- }
- return secretMessage.toString();
- }
- public static String decode(String line)
- {
- return encode(line,23);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement