2013-03-04 18 views
-1

如何能夠更改System.out我用它來檢查結果。
我需要測試這個方法。當輸出結果爲PrintStream時,最好做到這一點。
如何能夠解決這個問題?從System.out重構輸出到PrintStream

代碼:

private void scan(File file) { 
     Scanner scanner = null; 
     int matches = 0; 

     try { 
      scanner = new Scanner(file); 
     } catch (FileNotFoundException e) { 
      System.out.println("File Not Found."); 
      e.printStackTrace(); 
     } 

     while (scanner.hasNext()) 
      if (scanner.next().equals(whatFind)) { 
       matches++; 
      } 

     if (matches > 0) { 
      String myStr = String.format(
        "File: %s - and the number of matches " + "is: %d", 
        file.getAbsolutePath(), matches); 
      System.out.println(myStr); 
     } 
    } 

問:

  • 如何重構輸出System.outPrintStream

回答

1

嘗試使用此
PrintWriter out = new PrintWriter(System.out);

在最後不要忘了關閉它。
out.close();

注:out println()快於System.out.println()

修訂

import java.io.PrintStream; 
import java.io.PrintWriter; 

public class TimeChecker 
{ 
    public static void main(String[] args) 
    { 
     /** 
     * Normal System.out.println 
     */ 
     long start = System.currentTimeMillis(); 
     for(int i=1; i<1000000000; i++); 
     long end = System.currentTimeMillis(); 
     System.out.println((end-start)); 

     /** 
     * Using PrintWriter 
     * 
     * Note: The output is displayed only when you write "out.close()" 
     * Till then it's in buffer. So once you write close() 
     * then output is printed 
     */ 
     PrintWriter out = new PrintWriter(System.out); 
     start = System.currentTimeMillis(); 
     for(int i=1; i<1000000000; i++); 
     end = System.currentTimeMillis(); 
     out.println((end-start)); 

     /** 
     * Using PrintStream 
     */ 
     PrintStream ps = new PrintStream(System.out, true); 
     System.setOut(ps); 
     start = System.currentTimeMillis(); 
     for(int i=1; i<1000000000; i++); 
     end = System.currentTimeMillis(); 
     ps.println((end-start)); 

     // You need to close this for PrintWriter to display result 
     out.close(); 
    } 

} 

這會給你他們是如何工作和彼此不同的想法。
希望這有助於!

+0

不起作用。程序工作無止境。 – 2013-03-06 16:26:00

+0

@nazar_art我不明白「Program work endless」..你能解釋一下 – asifsid88 2013-03-06 17:50:07

+0

用'System.out'運行時間12s。有了這個變種沒有完成運行。等待很長時間,超過3分鐘。改回所有工作後好。 – 2013-03-06 17:55:01

0

嘗試像這樣:PrintStream匿名對象,它不會保證關閉流。但PrintWriter保證。

new PrintStream(System.out).print(str);  

這個答案我從PrintStream programming得到。

+0

我們不需要關閉'PrintStream'?最重要的是不正確的工作。如果'System.out'找到10個匹配的文件,這個變體只有一個+ doble運行時間! – 2013-03-06 16:34:11