我如何设置一个字符串变量并将其作为文件名传递到 File reader 扫描器中?

How would I set a string variable and pass it into a File reader scanner as a file name?

我正在编写一个 Cipher 程序,它要求用户输入文件名,将名称存储为变量,然后应该根据 String 变量读取文件。它可以编译,但是当我尝试 运行 它时,我不断收到 IOException。

 java.io.FileNotFoundException:  (No such file or directory)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.<init>(FileInputStream.java:146)
 at java.io.FileInputStream.<init>(FileInputStream.java:101)
 at java.io.FileReader.<init>(FileReader.java:58)
 at Cipher.main(Cipher.java:22)

我不明白发生了什么。它在用户更改键入文件名之前给出错误。这是我的代码:

import java.util.Scanner;
import java.io.*;

public class Cipher {

public static void main (String [] args) throws FileNotFoundException {

        String inFile = "";

        Scanner sc = new Scanner (System.in);
            System.out.println("Welcome to Caeser Cipher");
            System.out.println("Enter 1 to encipher, or 2 to decipher (-1 to exit): ");
            int cipher = sc.nextInt();

        System.out.println("What non-negative shift should I use?");
            int shift = sc.nextInt();

            System.out.println("What is the input file name?");
            inFile = sc.nextLine();
            try {

                Scanner input = new Scanner (new FileReader (inFile) ) ;
                String line = input.nextLine();



       /* System.out.println("What is the output file name?");
         String outFile = sc.nextLine();*/

        Scanner input = new Scanner (new FileReader (inFile) ) ;
        input.useDelimiter("['.!?0-9+");

        String line = input.nextLine();

        while (input.hasNextLine()) {

                line = input.nextLine();

                if (cipher == 1) {
                    System.out.println(caeserEncipher(line, shift));
                } else if (cipher == 2) {
                    System.out.println(caeserDecipher(line, shift));
                } else {
                    System.out.println ("Enter 1 to encipher, or 2 to decipher (-1 to exit)");
                    return;
                }
            }
        }

        catch (FileNotFoundException e) {
            System.out.println ("Trouble opening or reading the file...");
            System.out.println ("Perhaps it was misspelled!");
            e.printStackTrace();
        }
    }

   public static String caeserEncipher(String input, int shift) {
        int arr[] = new int[input.length()];
        StringBuilder builder = new StringBuilder();
        int length = input.length();
        String output = "";

        for (int i = 0; i < length; i++) {
            arr[i] = (int) input.charAt(i);
            arr[i] += shift;
        }

        for (int i = 0; i < length; i++) {
            builder.append((char)arr[i]);
        }

        output = builder.toString();
        return output;

}

public static String caeserDecipher(String input, int shift) {
int arr[] = new int[input.length()];
StringBuilder builder = new StringBuilder();
int length = input.length();
String output = "";

for (int i = 0; i < length; i++) {
    arr[i] = (int) input.charAt(i);
    arr[i] -= shift;
}

for (int i = 0; i < length; i++) {
    builder.append((char)arr[i]);
}

output = builder.toString();
return output;

    }

}

你的代码有问题

您在调用 scanner.nextInt() 之后直接调用 scanner.nextLine()

在这种情况下,如果您为 nextInt() 输入 5 并按回车键,那么它将 return 5 forscanner.nextInt()and换行forscanner.nextLine(). This occurs becausescanner.nextInt()doesn't consume the last newline leading tonextLinehaving换行. So, in your case, user will not get a chance to input the file-name leading to error and it would seem thatscanner.nextLine ()` 调用被跳过。

因此在调用 scanner.nextLine() 之前,在其上方添加另一个 scanner.nextLine() 以消耗最后一个新行。

就文件名而言,运行 你的程序有绝对路径,它应该 运行 没问题:像 D:\Work\file.txt

你的代码有很多错误。

  1. 多次申报input,line.
  2. 正则表达式错误。 "['.!?0-9+" 应该是 "\['.!?0-9+".
  3. scanner.nextLine() 之后未管理的换行符 (Enter)。

试试这个修改后的代码:-

import java.util.Scanner;
import java.io.*;

public class Cipher {

    public static void main(String[] args) throws FileNotFoundException {

        String inFile = "";

        // avoiding multtiple delcaration.
        Scanner input = null;
        String line = "";

        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome to Caeser Cipher");
        System.out.println("Enter 1 to encipher, or 2 to decipher (-1 to exit): ");
        int cipher = sc.nextInt();

        System.out.println("What non-negative shift should I use?");
        int shift = sc.nextInt();

        sc.nextLine(); // clearing '\n' (newline)
        System.out.println("What is the input file name?");
        inFile = sc.nextLine();
        try {

            input = new Scanner(new FileReader(inFile));
            line = input.nextLine();

            /*
             * System.out.println("What is the output file name?"); String outFile =
             * sc.nextLine();
             */

            input = new Scanner(new FileReader(inFile));
            input.useDelimiter("\['.!?0-9+");            // changed reg-expression

            line = input.nextLine();

            while (input.hasNextLine()) {

                line = input.nextLine();

                if (cipher == 1) {
                    System.out.println(caeserEncipher(line, shift));
                } else if (cipher == 2) {
                    System.out.println(caeserDecipher(line, shift));
                } else {
                    System.out.println("Enter 1 to encipher, or 2 to decipher (-1 to exit)");
                    return;
                }
            }
        }

        catch (FileNotFoundException e) {
            System.out.println("Trouble opening or reading the file...");
            System.out.println("Perhaps it was misspelled!");
            e.printStackTrace();
        }
    }

    public static String caeserEncipher(String input, int shift) {
        int arr[] = new int[input.length()];
        StringBuilder builder = new StringBuilder();
        int length = input.length();
        String output = "";

        for (int i = 0; i < length; i++) {
            arr[i] = (int) input.charAt(i);
            arr[i] += shift;
        }

        for (int i = 0; i < length; i++) {
            builder.append((char) arr[i]);
        }

        output = builder.toString();
        return output;

    }

    public static String caeserDecipher(String input, int shift) {
        int arr[] = new int[input.length()];
        StringBuilder builder = new StringBuilder();
        int length = input.length();
        String output = "";

        for (int i = 0; i < length; i++) {
            arr[i] = (int) input.charAt(i);
            arr[i] -= shift;
        }

        for (int i = 0; i < length; i++) {
            builder.append((char) arr[i]);
        }

        output = builder.toString();
        return output;

    }

}