PrintWriter not writing to file (Java)

前端 未结 2 627
失恋的感觉
失恋的感觉 2021-01-23 10:51

I am writing a kind of a cash machine program that will output the data into a file (Yes, I know its not in English, but that\'s not the point) and I am experiencing an error.

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-23 11:04

    Why are you opening and closing stream in your writeToFile call ? Shouldn't you open the streams in writeFooter() before the for loop, put a try block around the writing code, and close them in a finally section .

    The way I see it, You've openedstream first in the writeFooter, the you write printer.println("Проданные товары: ");, and then your for loop's first iteration calls writeToFile, will again open the non-closed stream, that will surely overwrite the first printed line.

    Opening and closing File for writing one line is way too inefficient.

    You need something like

    writeFooter(...) {
    
      try {
        openStreams();
        writeToFile();
      } finally {
        closeStream();
      }
    }
    

    Where writeToFile simply writes , doesn't open or close stream, and closeStream safely closes the streams, i.e. check for null etc.

提交回复
热议问题