[Java iO] copying arbitrary files with buffering

Source: Internet
Author: User
/*** Copy (byte stream) of any file with the buffer function (buffer size 8 K) * @ author mjn * @ date 2011-10-03 */public class filecopywithbuffer {public static void main (string [] ARGs) {inputstream in = NULL; outputstream out = NULL; byte [] Buf = new byte [8*1024]; int n =-1; // record the actual byte length of each read try {In = new fileinputstream ("1.jpg "); // file 1.jpg: Out = new fileoutputstream ("1_copy.jpg"); While (n = in. read (BUF ))! =-1) {/** if it is written as out. write (BUF), the last write is always 8 K Bytes * even if the number of bytes for the last read is not set to 8 K */out. write (BUF, 0, n) ;}} catch (filenotfoundexception e) {system. out. println ("file not found. ");} catch (ioexception e) {system. out. println ("error happened. ");} finally {try {If (in! = NULL) {in. Close () ;}if (OUT! = NULL) {out. Flush (); Out. Close () ;}} catch (exception e ){}}}}

In addition, to buffer and read files, you can also use bufferedinputstream:

        InputStream in = new BufferedInputStream(                new FileInputStream("in.txt"), 8 * 1024);

Note: during initialization, the buffer size should be an integer multiple of 1024 to optimize the underlying operations.

References:

The class source code of nnu instructor Jiang is 'java _ course'

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.