首页 > 解决方案 > PrintWriter 不将文本打印到文件

问题描述

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

      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");
    }

标签: java

解决方案


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

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


推荐阅读