java - 关闭打印流

标签 java file printstream bag

所以我基本上是在创建一个包,我被告知其中一个包必须包含至少 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/

相关文章:

java - 为什么这个基本的客户端-服务器程序不传递数据?

java - 通过 Java 扫描并打印同一文件

java - 限制客户端仅使用从 yml 文件创建的配置列表中的一个配置

java - 如何防止 Selenium 3.0 (Geckodriver) 创建临时 Firefox 配置文件?

java - 在 Java Eclipse 项目中查找未使用的类

c++ - 来自 getline 的 istringstream 为行中的最后一个元素返回 double

python - 使用文本文件中的数据在同一图形上绘制多个椭圆

c - 从 C 中的命令行管道传输文件

java - 在单个类上 hibernate 不同类型的一对一关系

java - 为什么我的writefile()无法编译?