/** * Write text content to a TXT file * @ Param Filecontent */ Public Void Writeresultfile (string filecontent ){ // File storage directory String filedir = Constdefine. file_dir; // File Name String filename = New Simpledateformat ("yyyymmddhhmmss"). Format ( New Date () + ". txt" ; File resultfile = New File (filedir, filename ); Bufferedreader = Null ; Bufferedwriter = Null ; Try {Bufferedreader = New Bufferedreader (New Stringreader (filecontent); bufferedwriter = New Bufferedwriter ( New Filewriter (resultfile )); Char Buf [] = New Char [1024]; // Character Buffer Int Len; While (LEN = bufferedreader. Read (BUF ))! =-1) {Bufferedwriter. Write (BUF, 0 , Len );}} Catch (Ioexception e) {e. printstacktrace ();} Finally { Try {Bufferedwriter. Flush (); bufferedreader. Close (); bufferedwriter. Close ();} Catch (Ioexception e) {e. printstacktrace ();}}}
The above method is to write the text content to the TXT file. There is no problem in the Windows system and the Red Hat Linux system, but it will become garbled after being written to the TXT file in the aix5.3 system.
The modified method is as follows: (encoding is added when the file is written)
/** * Write text content to a TXT file * @ Param Filecontent */ Public Void Writeresultfile (string filecontent ){ // File storage directory String filedir = Constdefine. file_dir; // File Name String filename = New Simpledateformat ("yyyymmddhhmmsszzz"). Format ( New Date () + ". txt" ; File resultfile = New File (filedir, filename); bufferedwriter = Null ; Try {Bufferedwriter = New Bufferedwriter (New Outputstreamwriter ( New Fileoutputstream (resultfile), "GBK" ); Bufferedwriter. Write (filecontent, 0 , Filecontent. Length ());} Catch (Ioexception e) {e. printstacktrace ();} Finally { Try {Bufferedwriter. Flush (); bufferedwriter. Close ();} Catch (Ioexception e) {e. printstacktrace ();}}}
The modified method does not contain garbled characters in windows, Linux, and Aix systems.
If you encounter garbled characters when reading files, you can also add the encoding:
Bufferedreader BR =NewBufferedreader (NewInputstreamreader (NewFileinputstream (NewFile (filepath), "GBK "));