2016-12-06 86 views
0

所以我基本上是創建一個包,我被告知我的包之一必須包含至少100000個元素。這不適合eclipse的控制檯窗口。所以將信息寫入文件似乎是一個更好的主意。我已經把我的主要方法和runBigBad方法放在這裏。正如你所看到的,在runBigBag之後,我想要做更多的事情。它編譯和運行良好。但是,它將runBigBag()調用後的所有內容都打印到文本文件中。我只想在文本文件中使用runBigBag()的內容,其餘部分則打印到控制檯窗口中。有人可以幫我嗎?當我嘗試使用finally子句並執行ps.close()時,它想要我初始化ps,然後使該文件爲空。所以我不知道該怎麼辦,除非有一個更簡單的方法。關閉一個打印流

public class TestBag { 

public static <E> void main(String[] args) { 
    //Start time for WHOLE PROGRAM 
    final long start = System.currentTimeMillis(); 
    //Run small bag 
    runSmallBag(); 
    //RESET COUNTERS TO ALLOW BIG BAG TO KEEP TRACK OF COMPLEXITY 
    Bag.resetCounters(); 
    //Run big bag 
    runBigBag(); 
    //Display the operation counters for each method used in whole program 
    System.out.println("Number of times add() was used for whole program: " + Bag.addCountA + "\n"); 
    System.out.println("Number of times remRand() was used for whole program: " + Bag.ranRemCountA + "\n"); 
    System.out.println("Number of times rem() was used for whole program: " + Bag.remCountA + "\n"); 
    System.out.println("Number of times contains() was used whole program: " + Bag.containsCountA + "\n"); 
    System.out.println("number of times addAll() was used whole program: " + Bag.addAllCountA + "\n"); 
    System.out.println("Number of times union() was used whole program: " + Bag.unionCountA + "\n"); 
    System.out.println("Number of times equal() was used whole program: " + Bag.equalsCountA + "\n"); 
    //End timer for whole program 
    final long end = System.currentTimeMillis(); 
    //Display timer for whole program 
    System.out.println("The whole program took " + ((end - start)*.001) + " seconds to run"); 
} 
public static <E> void runBigBag(){ 

    //Start time for big bag operations 
    final long start2 = System.currentTimeMillis(); 

    boolean prog = true; 

    //Create file to write bag too 
    File file = new File("bag.txt"); 
    PrintStream ps; 
    try { 
     ps = new PrintStream(new FileOutputStream(file)); 
     System.setOut(ps); 
    } catch (FileNotFoundException f) { 
     f.printStackTrace(); 
    } finally 
    //irrelevant code here 


    //End timer for big bag 
    final long end2 = System.currentTimeMillis(); 

    //Display timer for big bag 
    System.out.println("This part of the program took " + ((end2 - start2)*.001) + " seconds to run"); 

} 

}

回答

2

使用放樣變化如此之所有後續的System.out調用發送到您的文件寫入默認的輸出流。如果您不希望發生這種情況,請不要使用默認輸出流進行文件寫入。

您問題的最快答案就在這裏。 How do I create a file and write to it in Java?

0

雖然託什的答案可能會爲我工作好,我居然發現瞭如何做到這一點我希望的方式:

PrintStream ps; 
PrintStream stdout = System.out; 

我創建了一個使用默認的系統輸出和另一個爲PrintStream該方法的最後,我把:

System.setOut(stdout); 

我敢肯定,這大概會在我不打算爲背景的東西,但給我的輸出,我需要。感謝您的建議@Tosh。