2013-09-27 51 views
0

在下面的代码:关闭输出流'行为不端'?

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输出一些信息到控制台。一旦函数调用结束,我将'i'的值重定向到一个文本文件。这适用于循环的第一次迭代,但只要我调用'outStream.close()',就不会在下一次迭代(控制台或文件)中显示任何输出。有谁知道为什么会发生这种情况?另外什么是解决这个问题的方法?

+1

你为什么要写System.out?你为什么不直接写入文件? – vikingsteve

+0

包含更多代码,以便我们可以看到大图。 – hasan83

回答

2

关闭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(); 
0

您可以尝试outStream.flush()而不是outStream.close()内部循环。它可能工作。由于outStream.close();将关闭您的文件。完成循环后最好关闭。

0

既然你调用close()流布置因此不再存在了

1

循环后关闭文件

outStream.close(); 
+0

我试图在输出到txt文件和控制台之间切换,这就是为什么它在循环.... – fYre

+0

编辑你的答案,包括linearSurprise代码 – hasan83

2

这个假设是无效的:

'outStrem'已关闭,因此当我回想起我的功能时,输出将被发送到控制台 而不是文件。

为什么它会神奇地回到控制台?它只会被写入封闭流,这将导致一个异常,被PrintStream吞噬。

如果你想设置回原来的控制台流,你需要做的是明确的:

PrintStream originalOutput = System.out; 

// Do stuff... 

System.setOut(originalOutput); // Now we can write back to the console again 
1
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您完成后,一个后写它,而不是迭代它应该工作。

+0

我试图在输出到txt文件和控制台之间切换,这就是为什么它在循环中...... – fYre

+0

一旦你关闭了流,你需要创建一个新的能够写信给它。 – AppX

0

打印到文件如下:

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

和环路后关闭流。

Dont't setOut(outStream);