File copy,

Source: Internet
Author: User

File copy,

This question often appears during the written test. The following Code provides two implementation schemes.

 

1234567891011121314151617181920212223242526272829303132333435363738394041 import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.nio.ByteBuffer;import java.nio.channels.FileChannel; public final class MyUtil {     private MyUtil() {        throw new AssertionError();    }     public static void fileCopy(String source, String target) throws IOException {        try (InputStream in = new FileInputStream(source)) {            try (OutputStream out = new FileOutputStream(target)) {                byte[] buffer = new byte[4096];                int bytesToRead;                while((bytesToRead = in.read(buffer)) != -1) {                    out.write(buffer, 0, bytesToRead);                }            }        }    }     public static void fileCopyNIO(String source, String target) throws IOException {        try (FileInputStream in = new FileInputStream(source)) {            try (FileOutputStream out = new FileOutputStream(target)) {                FileChannel inChannel = in.getChannel();                FileChannel outChannel = out.getChannel();                ByteBuffer buffer = ByteBuffer.allocate(4096);                while(inChannel.read(buffer) != -1) {                    buffer.flip();                    outChannel.write(buffer);                    buffer.clear();                }            }        }    }}

Note: TWR of Java 7 is used above. After TWR is used, you do not need to release external resources in finally to make the code more elegant.

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.