I am trying to build a program that takes a text file, apply CaesarCipher method and returns and output file.
import java.util.*;
import java.io.*;
class CaesarCipher
{
public static void main (String [] args) throws FileNotFoundException {
System.out.print("What is the input file name? ");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.nextLine();
Scanner inputFile = new Scanner (new File (fileName));
String inputFileString = inputFile.toString();
System.out.print("What is the input file name? ");
int s = 4;
System.out.println("Text : " + inputFileString);
System.out.println("Shift : " + s);
System.out.println("Cipher: " + encrypt(inputFileString, s));
}
public static String encrypt(String inputFileString, int s) {
StringBuilder result = new StringBuilder();
for (int i=0; i< inputFileString.length(); i++) {
if (Character.isUpperCase(inputFileString.charAt(i))) {
char ch = (char)(((int)inputFileString.charAt(i) + s - 65) % 26 + 65);
result.append(ch);
}
else {
char ch = (char)(((int)inputFileString.charAt(i) + s - 97) % 26 + 97);
result.append(ch);
}
}
return result.toString();
}
}
I have two questions: 1- The program is compiling but when I run it and enter the text file name I get this error:
What is the input file name? Text : java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
2- How can I construct a new outPut file that contains the coded text?
It worked with StringBuilder
StringBuilder inputFileString = new StringBuilder();
while (inputFile.hasNext()) {
String x = inputFile.nextLine();
inputFileString.append(x);
}