Computer >> Máy Tính >  >> Lập trình >> Java

Tệp tạm thời trong Java

Trong một số trường hợp nhất định, chẳng hạn như kiểm tra đơn vị hoặc đối với một số lôgic ứng dụng, bạn có thể cần tạo tệp tạm thời.

Tạo tệp tạm thời

Lớp Tệp trong Java cung cấp một phương thức có tên createTempFile () . Phương thức này chấp nhận hai biến Chuỗi đại diện cho tiền tố (tên bắt đầu) và hậu tố (phần mở rộng) của tệp tạm thời và một đối tượng Tệp đại diện cho thư mục (đường dẫn trừu tượng) mà bạn cần tạo tệp.

Ví dụ

Ví dụ Java sau tạo một tệp tạm thời có tên là exampleTempFile5387153267019244721.txt trong đường dẫn D:/ SampleDirectory

import java.io.File;
import java.io.IOException;
public class TempararyFiles {
   public static void main(String args[]) throws IOException {
      String prefix = "exampleTempFile";
      String suffix = ".txt";
      //Creating a File object for directory
      File directoryPath = new File("D:/SampleDirectory");
      //Creating a temp file
      File.createTempFile(prefix, suffix, directoryPath);
      System.out.println("Temp file created.........");
   }
}

Đầu ra

Temp file created.........

Xóa tệp tạm thời

Lớp Tệp cung cấp phương thức delete () để xóa tệp hoặc thư mục hiện tại, gọi phương thức này trên tệp tạm thời.

Ví dụ

Chương trình Java sau tạo và xóa một tệp tạm thời.

import java.io.File;
import java.io.IOException;
public class TempararyFiles {
   public static void main(String args[]) throws IOException {
      String prefix = "exampleTempFile";
      String suffix = ".txt";
      //Creating a File object for directory
      File directoryPath = new File("D:/SampleDirectory");
      //Creating a temp file
      File tempFile = File.createTempFile(prefix, suffix, directoryPath);
      System.out.println("Temp file created: "+tempFile.getAbsolutePath());
      //Deleting the file
      tempFile.delete();
      System.out.println("Temp file deleted.........");
   }
}

Đầu ra

Temp file created: D:\SampleDirectory\exampleTempFile7179732984227266899.txt
Temp file deleted.........