所以我基本上创造了一个袋子,我被告知我的一个袋子必须包含至少100000个元素。这不适合eclipse的控制台窗口。因此,将信息写入文件似乎是一个更好的主意。我在这里放了我的main方法和runBigBad方法。正如您所看到的,在runBigBag之后,还有更多我想做的事情。它编译并运行良好。但是,它会在runBigBag()调用后将所有内容打印到文本文件中。我只想在文本文件中使用runBigBag()的内容,然后将其余内容打印到控制台窗口。有人可以帮我吗?当我尝试使用finally子句并执行ps.close()时,它希望我初始化ps然后使文件为null。所以除非有更简单的方法,否则我不知道该怎么做。
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");
}
}
答案 0 :(得分:2)
使用setOut正在更改默认输出流,以便将所有后续system.out调用发送到文件编写器。如果您不希望发生这种情况,请不要使用默认输出流进行文件编写。
您问题的最快答案就在这里。 How do I create a file and write to it in Java?
答案 1 :(得分:0)
虽然Tosh的回答对我来说可能更好,但我实际上发现了如何以我希望的方式做到这一点:
PrintStream ps;
PrintStream stdout = System.out;
我创建了另一个使用默认系统输出的PrintStream,在方法结束时,我输入了:
System.setOut(stdout);
我确信这可能会在我不想要的背景中做些什么,但是给了我需要的输出。谢谢你的建议@Tosh。