0

试图让用户输入要读取的输入文件,然后让输出文件“编码”输入文件。但是,我在处理输出文件时遇到了问题,可能还有输入文件,因为文件处理是我开始迷失 Java 的地方。

这应该是用于获取输入文件的方法。

public static Scanner getInputScanner(Scanner console){
Scanner input = null;
while (input == null) {
    System.out.print("Enter input file: ");
    String filename = console.next();
    try {
        input = new Scanner(new File(filename));
    }
    catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
}
return input;  
}

这应该是用于获取输出文件的方法。关于 PrintStream 的使用,我做错了什么吗?

//Returns PrintStream for output file
//Use a try/catch block to handle a FileNotFoundException
public static PrintStream getOutputPrintStream(Scanner console){
Scanner output = null;
while (output == null) {
    System.out.print("Enter output file: ");
    String filename = console.next();
    try {
        File file = new File(filename);
        PrintStream fileout = new PrintStream(file);
            if (file.exists()){
                System.out.print("OK to overwrite file? (y/n): ");
                String answer = console.next();
                    if (answer.equals("y")){
                    }
                    else if (answer.equals("n")){
                        System.exit(1);
                    }
            }
    }
    catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
}
return fileout;
}
4

0 回答 0