Hướng dẫn di chuyển file đến một thư mục khác trong Java

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();
		}
		
	}

}
0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
x