简体   繁体   中英

PrintWriter not printing text to file

I have an assignment to copy the text of one file to another. With the following code, I can print the lines of the file to the console, but it is not working to print to the output file.

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

Print writer uses Buffered writer. It will not write to the disk immediately. When you invoke println , printf , or format methods, it will write to the disk if automatic flushing is enabled. Otherwise you have to invoke flush method to write to disk. Usually invoking close method should write the whatever in the buffer to the file without the need of flush method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM