java临时文件下载
java.io.File class can be used to create temp file in java. Sometimes we need to create temporary files to be used by our application.
java.io.File类可用于在Java中创建临时文件。 有时我们需要创建临时文件以供我们的应用程序使用。
Java临时文件 (Java Temp File)
There are two methods in File
class that we can use to create temp file in java.
File
类中有两种方法可用于在Java中创建临时文件。
createTempFile(String prefix, String suffix, File directory)
: This method creates a temp file with given suffix and prefix in the directory argument.The directory should already be existing and should be a directory, else it throws exception.
The file name is created with random long number, so the file name becomes
prefix+random_long_no+suffix
.This is done to make the application safe as it will be impossible to guess the file name and since application has instance of temp file, we can use it. The prefix String should be minimum three characters long. If suffix is null, “.tmp” suffix is used.
If directory is null, then temp file is created in operating system temp directory.
createTempFile(String prefix, String suffix, File directory)
:此方法创建一个临时文件,在目录参数中具有给定的后缀和前缀。该目录应该已经存在,并且应该是目录,否则会抛出exception 。
文件名是使用随机
prefix+random_long_no+suffix
创建的,因此文件名变为prefix+random_long_no+suffix
。这样做是为了使应用程序安全,因为不可能猜测文件名,并且由于应用程序具有临时文件实例,因此我们可以使用它。 前缀字符串的长度至少应为三个字符。 如果后缀为null,则使用“ .tmp”后缀。
如果directory为null,则在操作系统的temp目录中创建临时文件。
createTempFile(String prefix, String suffix)
: It’s easy way to create temp file in operating system temp directory.createTempFile(String prefix, String suffix)
:这是在操作系统临时目录中创建临时文件的简便方法。
Java Temp文件示例 (Java Temp File Example)
Here is a small java temp file example program.
这是一个小的Java临时文件示例程序。
package com.journaldev.files;
import java.io.File;
import java.io.IOException;
public class JavaTempFile {
public static void main(String[] args) {
try {
File tmpFile = File.createTempFile("data", null);
File newFile = File.createTempFile("text", ".temp", new File("/Users/pankaj/temp"));
System.out.println(tmpFile.getCanonicalPath());
System.out.println(newFile.getCanonicalPath());
// write,read data to temporary file like any normal file
// delete when application terminates
tmpFile.deleteOnExit();
newFile.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of the above java temp file program is:
上面的Java临时文件程序的输出是:
/private/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/data225458400489752329.tmp
/Users/pankaj/temp/text2548249124983543974.temp
That’s all about creating temp file in java.
这就是在Java中创建临时文件的全部内容。
java临时文件下载