2013-06-21 98 views
0

進出口運行一些代碼,並期望得到送到Systen.err在一個點出來一個特定的消息,但由於某種原因它的現身在另一點。下面是代碼 -Eclipse的標準輸出/錯誤同步

public static void main(String[] args) throws Exception {  
     System.out.println("File 1:");  
     for (NormalizedEntity ne : theSolution.entities.values()){ 
      System.out.println(ne); 
     } 

     System.out.println("\nFile 2:"); 
     for (NormalizedEntity ne : theSubmission.entities.values()){ 
      System.out.println(ne); 
     } 
     System.out.println(check()); 
    } 

    static String check() { 
     StringBuilder resultString = new StringBuilder(); 

     System.out.println("\nstarting check"); 
     for (NormalizedEntity solutionEntity : theSolution.entities.values()){ 
      NormalizedEntity submissionEntity = theSubmission.entities.get(solutionEntity.name); 

      if(solutionEntity instanceof NormalizedClass){ 
       if(!(submissionEntity instanceof NormalizedClass)){ 
        System.err.println("***WARNING: solutionEntity " + solutionEntity + "is a class but submissionEntity " + submissionEntity + " is not");//<---This line should be second to last 
        resultString.append("Expected " + submissionEntity + " to be a class called " + solutionEntity); 
       }    
      } 

      //System.out.println("Found: " + ne + " in both"); 
     } 
     return resultString.toString(); 
    } 

,這裏是輸出 -

***WARNING: solutionEntity Class C {x=private int x, y=private int y} {C=C{1thParam=int, 2thParam=int}} {getX=int getX{}}is a class but submissionEntity null is not <--------- THIS LINE SHOULD BE AT THE END 
File 1: 
Class C {x=private int x, y=private int y} {C=C{1thParam=int, 2thParam=int}} {getX=int getX{}} 
Class SubC {z=private int z} {} {} 
C c 
double d 
int f{} 
int i 
SubC subC 

File 2: 
Class D {x=private int x, y=private int y} {D=D{1thParam=int, 2thParam=int}} {getX=int getX{}} 
Class SubC {z=private int z} {} {} 
D c 
double d 
int f{} 
int i 
SubC subC 

starting check 
Expected null to be a class called Class C {x=private int x, y=private int y} {C=C{1thParam=int, 2thParam=int}} {getX=int getX{}} 

現在基於代碼輸出的第一行應該是倒數第二行。但是,當我在eclipse中運行它時,它會作爲第一行出現。爲什麼是這樣?我還注意到,如果我將System.err更改爲System.out,則按預期發佈。所以看起來Eclipse首先收集所有的錯誤輸出,然後處理標準輸出?

+0

'err'優先,並立即被打印出來。我曾經有過在一行中間打印堆棧軌跡的情況。 – 2013-06-21 17:22:30

回答

1

寫入到兩個不同的流本質上是容易出現亂序顯示,但是,應該的System.out.println自動沖水每次調用的,也就是說,你所看到的情況應該是不可能的,或者在最壞的情況應該是能夠通過同步來緩解。

不幸的是,在Eclipse中的錯誤實際上阻止,這是正常工作,並導致出的順序,你看到線路:Synchronisation problem between System.out and System.err in the console

你可能要考慮使用一個日誌框架如的logback(+ SLF4J如果期望的)來允許您在保持一致的排序的同時記錄不同級別的消息。

相關問題