PrintWriter add text to file

不羁岁月 提交于 2019-12-01 09:25:25

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

PrintWriter outFile = new PrintWriter(new FileWriter("planetaryData.txt", true)); 

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));

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();
}

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!