开发者

Java: PrintWriter

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 MyFileW开发者_JS百科rite.java can't.

Could someone help me understand what am I missing here?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜