Java: PrintWriter

喜欢而已 提交于 2019-12-04 06:42:43

问题


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



来源:https://stackoverflow.com/questions/6734077/java-printwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!