Add to favorites Java

Source: Internet
Author: User

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 ");
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.