提问者:小点点

PrintSteam完全输出只创建最后一个数据集


我的程序编译并将写入一个。txt文件,但它只写入大小为1000的最后一个数据集。 我试图让它把所有十个大小写到一个。txt文件。 如果我去掉PrintSteam方法,完整的输出将包括所有10个数据集。 我如何使所有10个写到。txt文件? 下面是主代码和BenchmarkSorts类中写入文件的部分。

import java.io.IOException;
import java.io.FileNotFoundException;

public class SortMain {

    public static void main(String[] args) throws Exception, IOException, FileNotFoundException {
        int[] sizes = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
        new BenchmarkSorts(sizes);
    }
}
    try {
        // Creating a File object that represents the disk file. 
        PrintStream o = new PrintStream(new File("BenchmarkSort.txt")); 

        // Store current System.out before assigning a new value 
        PrintStream console = System.out; 

        // Assign o to output stream 
        System.setOut(o); 

        // Produces output
        System.out.println("Data Set Size (n): " + arraySize +
        "\n\tIterative Selection Sort Results: \t\t\t\t\tRecursive Selection Sort Results:" +
        "\n\tAverage Critical Operation Count: " + Math.round(iterativeAverageCount) +
        "\t\t\tAverage Critical Operation Count: " + Math.round(recursiveAverageCount) +
        "\n\tStandard Deviation of Count: " + Math.round(iterativeSDCount) +
        "\t\t\t\t\tStandard Deviation of Count: " + Math.round(recursiveSDCount) +
        "\n\tAverage Execution Time: " + Math.round(iterativeAverageTime) +
        "\t\t\t\t\t\tAverage Execution Time: " + Math.round(recursiveAverageTime) +
        "\n\tStandard Deviation of Time: " + Math.round(iterativeSDTime) +
        "\t\t\t\t\t\tStandard Deviation of Time: " + Math.round(recursiveSDTime));

         // Use stored value for output stream 
        System.setOut(console); 
        System.out.println("Output File is now BenchmarkSort.txt");
    } 
    catch(FileNotFoundException ex) {

    }

共1个答案

匿名用户

现在try-catch已经就绪(我仍然建议使用try-with-resource,这样everyhting get就会正确关闭!),您需要以附加的方式将输出流创建到文件中:

 //Create an appending file output stream
 FileOutputStream fo = new FileOutputStream(new File("BenchmarkSort.txt"), true);
 //Now create the print-stream
 PrintStream o = new PrintStream(fo);

现在,每次打开文件时,它都是以追加模式打开的--因此新的内容被写入到文件的末尾。

确保在返回之前关闭溪流! 使用try-with-resource已经为您实现了这一点:

 //Create an appending file output stream
 try(FileOutputStream fo = new FileOutputStream(new File("BenchmarkSort.txt"), true);
  //Now create the print-stream
  PrintStream o = new PrintStream(fo)) {



} // <- this will automatically close the streams!