Bài viết này chúng ta sẽ cùng tìm hiểu về cách để di chuyển một file đến một thư mục khác trong JavaJava.io.File không chứa bất kỳ phương thức nào đã xây dựng cho việc thực hiện di chuyển file, nhưng bạn có thể tự nghĩ ra cách với hai lựa chọn thay thế sau đây:

  1. File.renameTo ().
  2. Sao chép file sang thư mục mới và xóa file gốc.

Trong hai ví dụ dưới đây, chúng ta sẽ thực hiện qua 2 bước như trên:

1. File.renameTo()

package com.itphutran.file;

import java.io.File;

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

 File afile =new File("E:\\project\\huongdanjava\\javaio\\testFile.txt");

 if(afile.renameTo(new File("E:\\project\\huongdanjava\\javaio\\newFolder\\" + afile.getName()))){
 System.out.println("File is moved successful!");
 }else{
 System.out.println("File is failed to move!");
 }

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

Chạy ứng dụng ta được kết quả:

File is moved successful!

2. Copy và Delete File

package com.itphutran.file;

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 MoveFileExample {
	public static void main(String[] args) {
		InputStream inStream = null;
		OutputStream outStream = null;

		try {

			File afile = new File(
					"E:\\project\\huongdanjava\\javaio\\testFile.txt");
			File bfile = new File(
					"E:\\project\\huongdanjava\\javaio\\newFolder\\testFile.txt");

			inStream = new FileInputStream(afile);
			outStream = new FileOutputStream(bfile);

			byte[] buffer = new byte[1024];

			int length;
			// copy the file content in bytes
			while ((length = inStream.read(buffer)) > 0) {

				outStream.write(buffer, 0, length);

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

			// delete the original file
			afile.delete();

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

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

}
Previous articleRename file trong Java
Next articleHướng dẫn lấy ngày tạo file trong Java
Xin chào! Tôi là Phú Trần.Kiến thức nền tảng và tư duy tốt về hướng đối tượng. Không ràng buộc ở ngôn ngữ mà căn bản ở giải thuật và tư duy con người. Lập trình JAVA/PHP.

LEAVE A REPLY

Please enter your comment!
Please enter your name here