--I want to create a file in any directory. ――I want to make more than one, so I don't want the file name to be covered. --I want to use the created file temporarily and discard it.
An example of using the current milliseconds to make the file name unique. Of course, it cannot be said that it will not be worn. .. ..
python
//Get the current millisecond
long millTime = System.currentTimeMillis();
String fileName = "tmp_" + millTime + ".txt";
File file = new File(fileName);
Use the createTempFile method of the Files class. (Java 7 or later)
python
Files.createTempFile(Paths.get("Arbitrary directory"), "prefix", "suffix");
The following is an example of creating a temporary file, writing it, and then deleting it.
python
File file = null;
try {
Path tmpPath = Files.createTempFile(Paths.get("/tmp"), "prefix", ".suffix");
file = tmpPath.toFile();
//Write to file
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.write("Konjac");
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
//Delete file
if (file != null && file.exists()) {
file.delete();
}
}
Up to Java6, you can use the createTempFile method of the File class. reference https://docs.oracle.com/javase/jp/8/docs/api/java/io/File.html#createTempFile-java.lang.String-java.lang.String-java.io.File-
Recommended Posts