【问题标题】:PrintWriter not printing text to filePrintWriter 不将文本打印到文件
【发布时间】:2018-10-11 04:32:20
【问题描述】:

我的任务是将一个文件的文本复制到另一个文件。使用以下代码,我可以将文件的行打印到控制台,但无法打印到输出文件。

      try {
        System.out.print("Enter the file name with extension : ");

        Scanner input = new Scanner(System.in);

        File inputFile = new File(input.nextLine());
        PrintWriter out = new PrintWriter("/Users/jonathanzier/Dropbox/IdeaProjects/CSE_205_Homework1/src/com/company/output.txt");


        input = new Scanner(inputFile);


        while (input.hasNextLine()) {
            out.println(input.nextLine());
           //System.out.println(input.nextLine());  - This will print 
           //correctly to the console
        }
        out.close();


    } catch (FileNotFoundException e) {
        System.out.println("File Not Found");
    }

【问题讨论】:

  • 显示文件未找到错误
  • 尝试添加 out.flush(); out.println(input.nextLine());
  • @iamsankalp89 这是你的系统。如果文件没有找到,那么他应该会看到它。
  • @pavithraCS - 是的,这是为什么呢?谢谢
  • 现在我在循环中添加了 out.flush() 它可以正常工作。谢谢!

标签: java


【解决方案1】:

打印写入器使用缓冲写入器。它不会立即写入磁盘。当您调用printlnprintfformat 方法时,如果启用了自动刷新,它将写入磁盘。否则你必须调用flush 方法来写入磁盘。通常调用close 方法应该将缓冲区中的任何内容写入文件,而不需要flush 方法。

https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多