java創建臨時文件
The task is to create a temporary file in Java.
任務是用Java創建一個臨時文件。
Creating a temporary file
創建一個臨時文件
To create a temporary file in java – we use createTempFile() method of "File" class. The createTempFile() method is called with the File object which should be initialized with the file name (and path if you want to specify).
要在Java中創建一個臨時文件,我們使用“ File”類的createTempFile()方法 。 用File對象調用createTempFile()方法 ,該對象應使用文件名(和路徑,如果要指定)初始化。
The createTempFile() method returns a File object, and by using getName() method, we can access the temporary file name.
createTempFile()方法返回一個File對象,通過使用getName()方法 ,我們可以訪問臨時文件名。
This method accepts two arguments 1) file_name and 2) file_extension name. If the file_extension is null, the default file extension will be .tmp.
此方法接受兩個參數1) file_name和2) file_extension name。 如果file_extension為null ,則默認文件擴展名為.tmp 。
Package to use: import java.io.*;
要使用的包: import java.io. *;
Syntax:
句法:
//file object creation
File one = null;
File two = null;
//temporary file creation
one = File.createTempFile("file_name", "extension");
two = File.createTempFile("file_name", "extension");
Java代碼創建一個臨時文件 (Java code to create a temporary file)
// Java code to create a temporary file
import java.io.*;
public class Main {
public static void main(String[] args) {
//file object creation to store results
File one = null;
File two = null;
try {
//creating temporary file1 with extension '.javatemp'
one = File.createTempFile("sample1", ".javatemp");
//creating temporary file2 without using null
two = File.createTempFile("sample2", null);
System.out.println("file created: " + one.getPath());
System.out.println("file created: " + two.getPath());
} catch (IOException exp) {
System.out.println("Error in creating temporary file: " + exp);
}
}
}
Output
輸出量
file created: /tmp/sample14223766203657377545.javatemp
file created: /tmp/sample22708977934903691208.tmp
翻譯自: https://www.includehelp.com/java-programs/create-a-temporary-file-in-java.aspx
java創建臨時文件