Today, I want to write a TXT file, but the folder on the disk is not created. Before writing the file, you can determine that the file has not been created. When I went to the Internet to find Java to create TXT files and perform read and write operations, basically all of them came from a template. They all came from copy, which is annoying. Now, I will post what I wrote and show it to the children's shoes in need.
/*** Write TXT file ** @ Param conent * @ Param txtpath * @ Param isnextwriter true indicates to write the file in append form */Public void writertxt (string conent, string txtpath, boolean isnextwriter) {try {// create folders and files such as: F:/TXT Folder/testtxt/testdata.txt file = new file (txtpath); If (! File. getparentfile (). exists () {file. getparentfile (). mkdirs (); // create a folder, for example, create a/TXT Folder/testtxt/folder on drive F.} If (! File. exists () {file. createnewfile (); // create a TXT file such as testdata.txt file} // write the TXT file filewriter = new filewriter (txtpath, isnextwriter); bufferedwriter BW = new bufferedwriter (filewriter ); BW. newline (); BW. write (conent); filewriter. flush (); BW. close (); filewriter. close ();} catch (exception e) {e. printstacktrace ();}}
Test
Public static void main (string [] ARGs) {txtbean = new txtbean (); For (INT I = 0; I <100; I ++) {txtbean. writertxt ("testtxtdata" + I, "F:/TXT Folder/testtxt/testdata.txt", true );}}