Using Java programs to write files to disk encountered the problem: The file is not fully written.
If the content (Stringbuffer/stringbuilder) has 100W characters, but the Java program writes to the file but not 100W, some characters are missing.
The code is roughly like this:
1 Private void throws Exception {2 New File ("File_path"); 3 NULL ; 4 New OutputStreamWriter (new fileoutputstream (file)); 5 6 Osw.write ("A HUGE ... HUGE STRING "); 7 }
The file is generated. The content is not correct and only some characters are written.
I even wonder if Stringbuffer/stringbuilder also has a length limit? Because the characters are as many as the files are written each time.
Now think about it, it is a pattern Tucson broken ah.
Later, after the reminder, you flush it?
Then suddenly dawned.
The correct code should look like this:
1 Private voidWriteToDisk2 () {2File File =NewFile ("File_path");3OutputStreamWriter OSW =NULL;4 Try {5OSW =NewOutputStreamWriter (Newfileoutputstream (file));6 7Osw.write ("A HUGE ... HUGE STRING ");8 9}Catch(FileNotFoundException e) {Ten e.printstacktrace (); One}Catch(IOException e) { A e.printstacktrace (); -}finally { - Try { osw.flush (); osw.close (); -}Catch(IOException e) { - e.printstacktrace (); + } - } +}
Without flush, direct close is OK.
But the official Java documentation reminds you: Flush before close.
Closes the stream, flushing it first. Once The stream has been closed, further write () or flush () invocations'll cause an ioexception to be thrown. Closing a previously closed stream has no effect.
I shouldn't have made such a mistake.
School teachers are taught, open the flow must remember to close .
0 teacher, I'm sorry, I was wrong.
Because it is only a small test program, not so standard write try/catch, straight throw away.
Stop. Don't make excuses for yourself.
The small program also has its own rules/specifications, to be observed.
When using Java programs to write files, remember to flush ()