
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to create a file in a specified directory using Java
Problem Description
How to create a file in a specified directory?
Solution
This 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
Advertisements