Creation of Files in Java जावा में फाइल निर्माण
File creation is an essential part of file handling in Java. We use the `File` class from the java.io package to create new files.
जावा में फाइल हैंडलिंग का एक महत्वपूर्ण हिस्सा फाइल निर्माण है। हम नई फाइल बनाने के लिए java.io पैकेज की `File` क्लास का उपयोग करते हैं।
Key Points / मुख्य बिंदु:-
1. Use File class to create new files.
नई फाइल बनाने के लिए File क्लास का उपयोग करें।
2. `createNewFile()` method returns true if the file is created successfully.
`createNewFile()` मेथड true लौटाता है यदि फाइल सफलतापूर्वक बनती है।
3. If the file already exists, the method returns false.
यदि फाइल पहले से मौजूद है, तो मेथड false लौटाता है।
💻 Example 1: Create a File
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output 1 (If file does not exist):-
File created: myfile.txt
Output 2 (If file already exists):-
File already exists.
💻 Example 2: Check File Details After Creation
import java.io.File;
public class FileDetails {
public static void main(String[] args) {
File file = new File("myfile.txt");
if (file.exists()) {
System.out.println("File Name: " + file.getName());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Writable: " + file.canWrite());
System.out.println("Readable: " + file.canRead());
System.out.println("File Size in bytes: " + file.length());
} else {
System.out.println("The file does not exist.");
}
}
}
Possible Output:-
File Name: myfile.txt
Absolute Path: C:\Users\Admin\myfile.txt
Writable: true
Readable: true
File Size in bytes: 0
🔹 Real-life Uses / वास्तविक उपयोग:-
* Storing logs in applications
एप्लिकेशन में लॉग्स स्टोर करने के लिए
* Generating reports or text files dynamically
डायनामिक रिपोर्ट्स या टेक्स्ट फाइल्स बनाने के लिए
* Temporary file creation for backup or caching
बैकअप या कैशिंग के लिए अस्थायी फाइल निर्माण
Comments
Post a Comment