1

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?

Fady E
  • 346
  • 3
  • 16

3 Answers3

1

Your existing code doesn't actually read the input file into a String. You can do so with a number of methods, one such is Files.readAllLines(Path), which returns a List<String> of the file lines. Stream that, and collect it with line separators. Like,

String inputFileString = Files.readAllLines(new File(fileName).toPath()).stream()
            .collect(Collectors.joining(System.lineSeparator()));

As for writing to a file, take a look at the PrintStream(File) constructor.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

It worked with StringBuilder

StringBuilder inputFileString = new StringBuilder();
        while (inputFile.hasNext()) {
            String x = inputFile.nextLine();
            inputFileString.append(x);
        }
Fady E
  • 346
  • 3
  • 16
1

To fully answer your question:

  1. You are not really using the Scanner in a correct way. Here is a very good answer which shows several ways of how to convert an InputStream to a String. The only thing you need to know is how you would get an InputStream for a file (check code below). As a side note, you should always remember to close your resources. So close your FileInputStream if not used anymore (more details here).
    File file = new File("your/file/path/file.ending");
    try (FileInputStream fis = new FileInputStream(file)) {
        // your code here
    } catch (FileNotFoundException e){
        e.printStackTrace();
    }

  1. There are also multiple possibilities to create and write content to a file. Have a look at: How do I save a String to a text file using Java?

And to sum it all up I created a working example using a slighty different way for the implementation of the caesar encryption and using Files.lines(...) to read the files content and Files.write(...) to write the encrypted content to a new file:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Scanner;
import java.util.stream.Stream;

public class CaesarCipher {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);

        System.out.print("What is the input file name? ");
        Path filePath = Paths.get(scanner.nextLine());

        System.out.print("What is the output file name? ");
        Path encodedFilePath = Paths.get(scanner.nextLine());

        System.out.print("Caesar cipher offset? ");
        final int offset = Integer.parseInt(scanner.nextLine());

        // Retrieve a a stream of the input file, where each line is mapped using the encrypt function
        Stream<String> mappedFileStream = Files.lines(filePath).map(msg -> CaesarCipher.encrypt(msg, offset));

        // Write encrypted content to a new file using our mapped stream as an iterable
        Files.write(
                encodedFilePath,
                (Iterable<String>) mappedFileStream::iterator,
                StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

        // Decrypt the encoded file content and print it
        Files.lines(encodedFilePath)
                .map((fileLine) -> CaesarCipher.decrypt(fileLine, offset))
                .forEach(System.out::println);
    }

    public static String encrypt(String msg, int offset) {
        offset = offset % 26 + 26;
        StringBuilder encoded = new StringBuilder(msg.length());
        for (char i : msg.toCharArray()) {
            if (Character.isLetter(i)) {
                char base = Character.isUpperCase(i) ? 'A' : 'a';
                encoded.append((char) (base + (i - base + offset) % 26));
            } else {
                encoded.append(i);
            }
        }
        return encoded.toString();
    }

    public static String decrypt(String enc, int offset) {
        return encrypt(enc, 26 - offset);
    }
}
FlorianDe
  • 1,202
  • 7
  • 20