Java txt File from FileWriter is empty

前端 未结 2 920
长发绾君心
长发绾君心 2020-12-11 10:53

I have trouble with write txt file from class FileWrite in my java project , if the PRINT() method were in VehicleCollection class , and called in main class - don\'t have p

相关标签:
2条回答
  • 2020-12-11 11:03

    Since you are already using Java 7, why not use the try-with-resources construct to avoid having to do things like close streams:

    try( File   file = new File("krasiWrite.txt"); 
         Writer writer = new BufferedWriter(new java.io.FileWriter(file)); )
    { 
         String text = getArrList().toString();
         writer.write(text);
         writer.flush(); // this lines takes whatever is stored in the BufferedWriter's internal buffer
                         // and writes it to the stream
    }
    catch(IOException ioe) {
       // ... handle exception
    }
    
    // now all resources are closed.
    
    0 讨论(0)
  • 2020-12-11 11:04

    File writes are usually buffered by the operating system. You must either close() or flush() the writer to make sure that the changes go to disk. If you're done with the file, just close it. A close will automatically flush the buffers.

    0 讨论(0)
提交回复
热议问题