How to create a file in a specified directory?
SolutionThis example demonstrates how to create a file in a specified directory using File.createTempFile() method of File class.
import java.io.File; public class Main { public static void main(String[] args) throws Exception { File file = null; File dir = new File("C:/"); file = File.createTempFile("JavaTemp", ".javatemp", dir); System.out.println(file.getPath()); } }Result
The above code sample will produce the following result.
C:\JavaTemp37056.javatemp
The following is an example of file in a specified directory.
import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateFile { public static void main(String[] args) throws IOException { Path p1 = Paths.get("C:/"); Files.createDirectories(p1.getParent()); try { Files.createFile(p1); } catch (FileAlreadyExistsException e) { System.err.println("already exists: " + e.getMessage()); } } }
The above code sample will produce the following result.
BUILD SUCCESSFUL
java_files.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4