gpt4 book ai didi

java - 关闭打印流

转载 作者:行者123 更新时间:2023-12-02 03:11:28 27 4
gpt4 key购买 nike

所以我基本上是在创建一个包,我被告知其中一个包必须包含至少 100000 个元素。这不适合 eclipse 的控制台窗口。因此将信息写入文件似乎是一个更好的主意。我已将 main 方法和 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");

}

}

最佳答案

使用 setOut 会更改您的默认输出流,以便所有后续的 system.out 调用都会发送到您的文件编写器。如果您不希望发生这种情况,请不要使用默认输出流进行文件写入。

您的问题的最快答案就在这里。 How do I create a file and write to it in Java?

关于java - 关闭打印流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987154/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com