Home > File > Di chuyển file sang một thư mục khác trong Java

Di chuyển file sang một thư mục khác trong Java

Java.io.File không có sẵn phương thức để di chuyển file, nhưng bạn có thể khắc phục bằng cách sau :

  • Cách 1 : Sử dụng File.renameTo()
  • Cách 2 : Copy sang 1 file mới và xóa file gốc đi

Ví dụ 1 : Sử dụng File.renameTo()

package quyetdv.java.javaio.file;
import java.io.File;
public class MoveFileUsingRenameToExample {
    public static void main(String[] args) {
        try {
            File aFile = new File("C:\\folderA\\Afile.txt");
            if (aFile.renameTo(new File("C:\\folderB\\" + aFile.getName()))) {
                System.out.println("File is moved successful!");
            } else {
                System.out.println("File is failed to move!");
            }
       } catch (Exception e) {
            e.printStackTrace();
       }
   }
}

Ví dụ 2 : Sử dụng Copy và Delete

package quyetdv.java.javaio.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFileUsingCopyDeleteExample {
    public static void main(String[] args) {
        InputStream is = null;
        OutputStream os = null;
        try {
            File aFile = new File("C:\\folderA\\aFile.txt");
            File bFile = new File("C:\\folderB\\bFile.txt");
            is = new FileInputStream(aFile);
            os = new FileOutputStream(bFile);
            byte[] buffer = new byte[1024];
            int length;
            // copy the file content in bytes
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            is.close();
            os.close();
            // delete the original file
            aFile.delete();
            System.out.println("File is copied successful!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Advertisements
Categories: File
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: