Java - Hướng dẫn tạo ứng dụng copy file bằng Java 7.(Copy file with Java 7 Files class).





Bài viết hôm nay sẽ tiếp tục giới thiệu thêm một phương thức sao chép tập tin bằng Java 7.

Ở bài viết này bạn sẽ sử dụng lớp(class) File và phương thức(Method) để sao chép một một tập tin.





Bên dưới là phương thức sao chép tập tin sử dụng lớp file File của Java 7.
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

Đơn giản quá nên khỏi mô tả nha ^^! còn dưới đây là toàn bộ source code example:
 import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;

import org.apache.commons.io.FileUtils;

public class CopyFileBasic {
  
    public static void main(String[] args) {
        // TODO, add your application code
        try {
            File fa = new File("Path File A");
            File fb = new File("Path File B");          
            //copyFileUsingStream(fa, fb);
            //copyFileUsingChannel(fa, fb);
            copyFileUsingApacheCommonsIO(fa, fb);
          
        } catch (IOException io) {
          
        }   

    }
  
    private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
        Files.copy(source.toPath(), dest.toPath());
    }  
  
    private static void copyFileUsingChannel(File source, File dest) throws IOException {
        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        try {
            sourceChannel = new FileInputStream(source).getChannel();
            destChannel = new FileOutputStream(dest).getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
           }finally{
               sourceChannel.close();
               destChannel.close();
           }
    }  
  
    private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }
  
    private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
        FileUtils.copyFile(source, dest);
    }      
  
}

Mọi thắc mắc và ý kiến đóng góp xin vui lòng chia sẻ tại đây TT^TT lâu rùi không thấy ai comment buồn quá.













No comments:

Post a Comment