Import java. Io. bufferedwriter;
Import java. Io. fileoutputstream;
Import java. Io. filewriter;
Import java. Io. ioexception;
Import java. Io. outputstreamwriter;
Import java. Io. randomaccessfile;
/**
* Description: append the content to the end of the file.
* @ Author Administrator
*
*/
Public class writestreamappend {
/**
* Append file: Use fileoutputstream to set the second parameter to true when constructing fileoutputstream.
*
* @ Param filename
* @ Param content
*/
Public static void Method1 (string file, string conent ){
Bufferedwriter out = NULL;
Try {
Out = new bufferedwriter (New outputstreamwriter (
New fileoutputstream (file, true )));
Out. Write (conent );
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Try {
Out. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
/**
* Append a file: Use filewriter
*
* @ Param filename
* @ Param content
*/
Public static void method2 (string filename, string content ){
Try {
// Open a file writer. The second parameter true in the constructor indicates that the file is written as an append object.
Filewriter writer = new filewriter (filename, true );
Writer. Write (content );
Writer. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
/**
* Append a file: Use randomaccessfile
*
* @ Param filename
* File name
* @ Param content
* Append content
*/
Public static void method3 (string filename, string content ){
Try {
// Open a random access file stream in read/write mode
Randomaccessfile randomfile = new randomaccessfile (filename, "RW ");
// File length, number of bytes
Long filelength = randomfile. Length ();
// Move the Write File pointer to the end of the file.
Randomfile. Seek (filelength );
Randomfile. writebytes (content );
Randomfile. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
Public static void main (string [] ARGs ){
System. Out. println ("START ");
Method1 ("C:/test.txt", "append to the end of the file ");
System. Out. println ("end ");
}
}