PrintWriter add text to file

后端 未结 4 1103
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 13:27

In my online computer science class I have to write a program to determine the surface gravity on each planet in the solar system. I have gotten almost every aspect of it to

相关标签:
4条回答
  • 2021-01-14 13:53

    Two problems:

    1) You are overwriting the file each time. printResultsToFile should take the whole array, not just one datum. Call it from outside your loop.

    2) Consider entering your floating point numbers as 2.08e24 for brevity.

    private void printResultsToFile(double result[]) {
      PrintWriter pw = new PrintWriter(new FileWriter("planetaryData.txt"));
      for (int i=0; i< result.length; i++) {
        pw.printf("%.2f%n", result[i]);
      }
      pw.close();
    }
    
    0 讨论(0)
  • 2021-01-14 13:58

    the following code also works to open file name planetaryData.txt.

    PrintWriter outFile = new PrintWriter("planetaryData.txt");

    0 讨论(0)
  • 2021-01-14 14:07

    Do this in order to create a PrinterWriter working with a FileWriter in append mode:

    PrintWriter outFile = new PrintWriter(new FileWriter("planetaryData.txt", true)); 
    
    0 讨论(0)
  • 2021-01-14 14:11

    From Mkyong's tutorials:

    FileWriter, a character stream to write characters to file. By default, it will replace all the existing content with new content, however, when you specified a true (boolean) value as the second argument in FileWriter constructor, it will keep the existing content and append the new content in the end of the file.

    You can use something like -

        PrintWriter outputFile = new PrintWriter(new FileWriter(file, true));
    
    0 讨论(0)
提交回复
热议问题