Lấy địa chỉ nơi lưu file tạm trong Java

Khi bạn tạo file tạm trong Java, bạn biết nó được lưu ở đâu trong ổ đĩa máy tính chứ?

Lấy địa chỉ nơi lưu file tạm trong Java
File tạm trong Java

Chưa biết thì giờ biết bạn nhé. Để lấy địa chỉ nơi lưu file tạm trong Java, đơn giản bạn chỉ cần dùng phương thức getAbsolutePath() của lớp File.

Ví dụ lấy địa chỉ nơi lưu file tạm

package com.ngockhuong;

import java.io.File;
import java.io.IOException;

public class GetTempFilePathExample {
	public static void main(String[] args) {
		try {
			// tạo file tạm
			File temp = File.createTempFile("filetam", ".tmp");

			System.out.println("File tạm: " + temp.getAbsolutePath());

			// lấy đường dẫn file tạm
			String absolutePath = temp.getAbsolutePath();
			String tempFilePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));

			System.out.println("Đường dẫn file tạm: " + tempFilePath);

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

Kết quả

Trên Linux (test trên Linux Mint)

File tạm: /tmp/filetam660954145435390300.tmp
Đường dẫn file tạm: /tmp

Trên Windows

File tạm: C:\Users\ngockhuong\AppData\Local\Temp\filetam69553461.tmp
Đường dẫn file tạm: C:\Users\ngockhuong\AppData\Local\Temp

 

0 0 votes
Đánh giá bài viết
Nhận thông báo
Thông báo khi có
guest

0 Bình luận
Phản hồi nội tuyến
Xem tất cả các bình luận