java create file and parent directories

www.la‮tu‬turi.com
java create file and parent directories

To create a file and its parent directories in Java, you can use the mkdirs method of the File class.

For example, to create a file called "output.txt" in the directory "C:\temp\files", you can use the following code:

File file = new File("C:\\temp\\files\\output.txt");
file.getParentFile().mkdirs();
file.createNewFile();

This creates the directory "C:\temp\files" and the file "output.txt" inside it. If the directory already exists, the mkdirs method does nothing.

You can also use the createTempFile method of the File class to create a temporary file in a specific directory. For example, to create a temporary file in the "C:\temp" directory, you can use the following code:

File file = File.createTempFile("temp", ".txt", new File("C:\\temp"));

This creates a new temporary file called "temp*.txt" in the "C:\ temp" directory, where "*" is a unique number. The file is deleted when the program exits.

Created Time:2017-11-03 00:14:52  Author:lautturi