-1
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 吗?我评论了那部分,但它仍然不起作用。

4

3 回答 3

0

为什么使用:

outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));

为什么不直接使用:

PrintWriter outputStream = new PrintWriter("text.txt");

于 2013-03-04T19:26:22.250 回答
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(); 
        }
    }
}
于 2013-03-04T19:26:24.313 回答
0

outputStream在写信之前就关闭了。

请注意,该finally总是在 try 块退出时执行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();
}
于 2013-03-04T19:27:40.327 回答