【问题标题】:Output stream doesn't print anything输出流不打印任何东西
【发布时间】:2013-03-04 19:23:27
【问题描述】:
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 吗?我把那部分注释掉了,但它仍然不起作用。

【问题讨论】:

  • outputStream 在哪里声明?你的意思是output?另外,如果你关闭它,你就不能再写了。
  • 是的,我一直在想……这没有意义,但为什么有人会给我这个作为演示代码?

标签: java outputstream printwriter


【解决方案1】:

为什么使用:

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

为什么不直接使用:

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

【讨论】:

【解决方案2】:

在关闭流之前编写你的 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(); 
        }
    }
}

【讨论】:

    【解决方案3】:

    在写信之前你要关闭outputStream。

    请注意,finally 块总是在 try 块退出时执行。 所以你必须在退出try 块之前写信给outputStream。

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

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2016-12-11
      • 2018-12-03
      • 1970-01-01
      相关资源
      最近更新 更多