本文介绍了Java:PrintWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PrintWriter.java ,但我遇到了一个相当奇怪的问题,我无法弄清楚我在这里缺少什么。

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 被愉快地写入的 myFileName.txt 文件但不能

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?

推荐答案

你可能需要您的印刷作家。

You probably need to flush your print writer.

在创建一个带有 autoFlush 设置为关闭

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

调用 pw.flush() pw.close(); 之前应该这样做

这篇关于Java:PrintWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:18