PrintWriter flush在Windows Server 2012上不起作用

时间:2017-10-24 00:51:30

标签: java windows flush printwriter

我使用PrintWriter写入autoFlush = true的文件: PrintWriter pw = new PrintWriter(new FileOutputStream(file),autoFlush);

不调用pw.flush(),每次调用pw.println(...)时,内容都会写入输出文件。

它在Win7和Win Server 2008上工作正常但不是Win Server 2012.我尝试使用相同的JDK,对于Win Server 2012 env,文件仅在finally块中调用pw.close()后刷新(例如到达终点)程序或异常发生)。

根据javadoc:https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html#flush()

如果此流的预期目标是底层操作系统提供的抽象,例如文件,则刷新流只保证先前写入流的字节被传递给操作系统进行写入;它并不保证它们实际上是写入物理设备,如磁盘驱动器。

似乎是操作系统问题。对此有何帮助?

这里是代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class TestPW {
    public static void main(String[] args) throws Exception {

        File file = null;
        PrintWriter pw = null;

        try {
            boolean autoFlush = true;

            file = new File("C:\\NotBackedUp\\test.txt");
            pw = new PrintWriter(new FileOutputStream(file), autoFlush);

            int loop = 100000000;

            while (loop > 0) {
                pw.println("Test: " + loop);
                loop--;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            } catch (Exception e) {

            }
        }

    }
}

解决方法是在处理了一些循环后关闭pw并再次重新启动pw对象,如下所示....

import java.io.*;

public class TestPSMaxLine {
    public static void main(String[] args) throws Exception {

        File file = null;
        PrintStream ps = null;

        int maxLinesToWriteBeforeClose = 100000;

        try {
            boolean appendFile = true;
            boolean autoFlush = true;

            file = new File("C:\\NotBackedUp\\test.txt");
            ps = new PrintStream(new FileOutputStream(file, appendFile), autoFlush);

            int loop = 100000000;
            int lineNum = 0;

            while (loop > 0) {
                ps.println("Test: " + loop);
                loop--;
                lineNum++;
                if(lineNum % maxLinesToWriteBeforeClose ==0){
                    closeFile(ps);
                    ps = new PrintStream(new FileOutputStream(file, appendFile), autoFlush);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeFile(ps);
        }
    }

    private static void closeFile(PrintStream ps){
        try{
            if (ps != null) {
                ps.close();
            }   
        } catch (Exception e) { 
        }
    }
}

1 个答案:

答案 0 :(得分:0)

有一个例外,但PrintWriter吞下了异常。您需要手动检查它们。或者使用BufferedWriter,它不会吞下异常。