-->

Java: PrintWriter

2019-03-06 15:50发布

问题:

I am trying to use PrintWriter.java but I am getting a rather strange problem and I am not able to figure out what am I am missing here.

MyPrintWriter.java

public class MyPrintWriter {

    public static void main(String[] args) {

        File myFile = new File("myFileDirectory/myFileName.txt");
        try {

            FileWriter fw = new FileWriter(myFile);
            PrintWriter pw = new PrintWriter(fw);
            pw.println("Hello World!");

            pw.close();

        }   catch (FileNotFoundException e) {
                System.err.println("File not found: " + myFile);
        }   catch (Exception e) {
                e.printStackTrace();
        }       
    }

}

MyFileWriter.java

public class MyFileWriter {
    public static void main(String[] args) {

        File myFile = new File("myFileDirectory/myFileName.txt");
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);

            FileWriter fw = new FileWriter(myFile);
            PrintWriter pw = new PrintWriter(fw);

            String input;
            input = br.readLine();
            while(input != null) {
                pw.println(input);
                input = br.readLine();
            }           
            br.close();
            pw.close();

        }   catch (FileNotFoundException e) {
                System.err.println("File not found: " + myFile);
        }   catch (Exception e) {
                e.printStackTrace();
        }       
    }

}

MyPrintWriter.java is happily writing to the myFileName.txt file but MyFileWrite.java can't.

Could someone help me understand what am I missing here?

回答1:

You probably need to flush your print writer.

The PrintWriter constructor with a FileWriter parameter creates a PrintWriter with autoFlush set to off

Calling pw.flush() before pw.close(); should do the trick