输出流不打印任何内容

时间:2013-03-04 19:23:27

标签: java outputstream printwriter

public class Demo
{
    public static void main(String[] args)
    {
        PrintWriter outputStream= null;
        try
        {
            outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error");
            System.exit(0);
        }
        finally {
                if (outputStream!= null)
                    outputStream.close(); 
        }


        outputStream.println("Hahahahaha");



    }
}

所以我得到了这个示例代码,但奇怪的是它根本不起作用,因为当我打开文本文件时。它完全是空白的。怎么可能?是因为output.close?我评论说,但它仍然不起作用。

3 个答案:

答案 0 :(得分:0)

为什么要使用:

outputStream = new PrintWriter(new BufferedWriter(new PrintWriter(“text.txt”)));

为什么不使用:

PrintWriter outputStream = new PrintWriter(“text.txt”);

答案 1 :(得分:0)

在关闭流之前写下你的println语句

public class Demo
{
    public static void main(String[] args)
    {
        PrintWriter outputStream = null;
        try
        {
            outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));
        outputStream.println("Hahahahaha");
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error");
            System.exit(0);
        }
        finally {
                if (outputStream != null)
                    outputStream.close(); 
        }
    }
}

答案 2 :(得分:0)

在写入之前,您正在关闭outputStream

请注意,当{try}块退出时,finally始终会执行。 因此,在退出outputStream块之前,您必须先写入try

关闭它,你会看到你输入的文字。

try
{
    outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));
    outputStream.println("Hahahahaha");
}
catch(FileNotFoundException e)
{
    System.out.println("Error");
    System.exit(0);
}
finally {
    if(outputStream != null)
       outputStream.close();
}