文件 I/O:从一个文件读取并写入另一个文件 (Java)

新手上路,请多包涵

我目前正在我的 cpe 课程的实验室工作,我们必须创建一个简单的程序来扫描 .txt 文件中的字符串并将它们打印到不同的 .txt 文件。到目前为止,我已经制定了基本程序,但是尽管我拥有所有必要的文件,但我的异常不断抛出。谁能帮我调试?

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

public class FileIO {

public static void main(String args[]) {
    try {
        File input = new File("input");
        File output = new File("output");
        Scanner sc = new Scanner(input);
        PrintWriter printer = new PrintWriter(output);
        while(sc.hasNextLine()) {
            String s = sc.nextLine();
            printer.write(s);
        }
    }
    catch(FileNotFoundException e) {
        System.err.println("File not found. Please scan in new file.");
    }
}
}

原文由 Mike 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 734
2 个回答

您需要弄清楚它在哪里寻找 "input" 文件。当您仅指定 "input" 时,它会在 当前工作目录 中查找文件。使用 IDE 时,此目录可能与您想象的不同。

尝试以下操作:

 System.out.println(new File("input").getAbsolutePath());

查看它在哪里查找文件。

原文由 aioobe 发布,翻译遵循 CC BY-SA 3.0 许可协议

可能你只是忘记了 flush()

        try {
            File input = new File("input");
            File output = new File("output");
            Scanner sc = new Scanner(input);
            PrintWriter printer = new PrintWriter(output);
            while (sc.hasNextLine()) {
                String s = sc.nextLine();
                printer.write(s);
            }
            **printer.flush();**
        }
        catch (FileNotFoundException e) {
            System.err.println("File not found. Please scan in new file.");
        }

原文由 isvforall 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题