簡體   English   中英

關閉輸出流“行為異常”?

[英]Closing output stream 'misbehaving'?

在下面的代碼中:

    for(int i = 5; i  <= 100; i+=5)
    {
        linearSurprise(i); // Function calling 'System.out.print()'

        System.setOut(outStream); // Reassigns the "standard" output stream.

        System.out.println("Value of i: " + i); // Outputting the value to the .txt file.

        outStream.close(); // 'outStrem' is closed so that when I recall my function, output will 
                           // will be sent to the console and not file.

      // After debugging, I notice that nothing is being displayed to either the console or file, 
      // but everything else is still working fine. 
    }

我將函數稱為“ linearSurprise”,並在該函數中向控制台輸出一些信息。 函數調用結束后,我將'i'的值重定向到文本文件。 這適用於循環的第一次迭代,但是當我調用'outStream.close()'時,在下一次迭代(控制台或文件)中將不會顯示任何輸出。 有人知道為什么會這樣嗎? 另外,解決此問題的方法是什么?

您要關閉 OutputStream你的循環里面System.out現在是封閉的; 您必須為其重新分配一個打開的OutputStream才能寫入更多輸出。

為此,您實際上應該直接寫到FileOutputStream System.out重定向到它沒有任何價值,這會導致類似這樣的問題。

PrintStream outStream = new PrintStream(File outputFile);
for(int i = 5; i <= 100; i += 5)
{
    linearSurprise(i);
    outStream.println("Value of i: " + i);
}
outStream.close();

此假設無效:

'outStrem'已關閉,因此當我調用函數時,輸出將發送到控制台而不是文件。

為什么會神奇地回到控制台? 而是將其寫入封閉的流中,這將導致異常,該異常被PrintStream吞沒。

如果要將其設置回原始控制台流,則需要明確地執行以下操作:

PrintStream originalOutput = System.out;

// Do stuff...

System.setOut(originalOutput); // Now we can write back to the console again

循環后關閉文件

outStream.close();
System.setOut(outStream); // Reassigns the "standard" output stream.
for(int i = 5; i  <= 100; i+=5)
    {
        linearSurprise(i); // Function call


        System.out.println("Value of i: " + i); // Outputting the value to the .txt file.

will 
                           // will be sent to the console and not file.

      // After debugging, I notice that nothing is being displayed to either the console or file, 
      // but everything else is still working fine. 
    }
    outStream.close(); // 'outStrem' is closed so that when I recall my function, output 

如果您在完成寫入后關閉outStream,而不是經過一次迭代,則它應該可以工作。

您可以在循環內嘗試使用outStream.flush()而不是outStream.close() 它可能會起作用。 作為outStream.close(); 將關閉您的文件。 最好在循環完成后關閉。

由於您調用CLose(),因此流已被處置,因此不再存在

打印到文件,如下所示:

outStream.println("What ever you want");

並在循環后關閉流。

不要setOut(outStream);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM