Làm thế nào để di chuyển một tập tin tới một thư mục khác? (How to move file to another folder in Java?)






Điều đáng buồn là lớp Java.io.File không có bất kỳ phương pháp hỗ trợ nào để di chuyển(move) một tập tin từ một folder này sang folder khác. Vì vậy trong bài viết này tôi sẽ hướng dẫn cách di chuyển(move) một tập tin trong Java.







Do lớp IO không hỗ trợ phương pháp move tập tin, nên ta sẽ thực hiện công việc này bằng cách kết hợp phương pháp copy một tin xóa một tập tin mà tôi đã giới thiệu trong các bài viết trước đâu.

Để thực hành tôi có một hình ảnh sau và một thư mục như sau:


Công việc của chúng ta là sao chép(copy) tập tin "IMAGE_01.png" vào thư mục "FOLDER" ở kế bên và xóa tập tin hình ảnh gốc(original), để thực hiện ta sử dụng đoạn mã bên dưới.

/**
 * @(#)JavaMoveFileExample.java
 *
 * JavaMoveFileExample application
 *
 * @author developer.bnson@gmail.com
 * @version 1.00 2014/3/15
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class JavaMoveFileExample {
   
    public static void main(String[] args) {

        InputStream inStream = null;
        OutputStream outStream = null;

        try{

            File rootfile =new File("D:\\Z-Test\\Demo\\IMAGE_01.png");
            File movefile =new File("D:\\Z-Test\\Demo\\FOLDER\\IMAGE_01.png");

            inStream = new FileInputStream(rootfile);
            outStream = new FileOutputStream(movefile);

            byte[] buffer = new byte[1024];

            int length;
           
            // Copy the file content in bytes.
            // Sao chép nội dụng tập tin dưới dạng bytes.
            while ((length = inStream.read(buffer)) > 0){

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();

            // Delete the original file.
            // Xóa tập tin gốc.
            rootfile.delete();

            System.out.println("File copy is successful!");

        }catch(IOException e){
            e.printStackTrace();
           
        }
       

    }
}

Sau khi tập tin được di chuyển thành công bạn sẽ nhận được thông báo như sau:

File copy is successful!

Bây giờ ta sẽ kiểm tra thư mục "D:\Z-Test\Demo" còn tồn tại tập tin hình ảnh hay không?


Như hình trên bạn thấy tại thư mục "DEMO" hình ảnh "IMAGE_01.png" đã bị mất và xuất hiện hiện trong thư mục "FOLDER"































No comments:

Post a Comment