关闭一个打印流
问题描述:
所以我基本上是创建一个包,我被告知我的包之一必须包含至少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");
}
}
答
使用放样变化如此之所有后续的System.out调用发送到您的文件写入默认的输出流。如果您不希望发生这种情况,请不要使用默认输出流进行文件写入。
您问题的最快答案就在这里。 How do I create a file and write to it in Java?
答
虽然托什的答案可能会为我工作好,我居然发现了如何做到这一点我希望的方式:
PrintStream ps;
PrintStream stdout = System.out;
我创建了一个使用默认的系统输出和另一个为PrintStream该方法的最后,我把:
System.setOut(stdout);
我敢肯定,这大概会在我不打算为背景的东西,但给我的输出,我需要。感谢您的建议@Tosh。