File Handling in Java जावा में फ़ाइल हैंडलिंग
जावा में फ़ाइल हैंडलिंग के द्वारा हम सिस्टम पर फाइल को बनाना, पढ़ना, लिखना और प्रबंधित कर सकते हैं। यह java.io पैकेज का हिस्सा है जो फ़ाइल हैंडलिंग के लिए कई क्लास और मेथड उपलब्ध कराता है।
🔹 Common Classes for File Handling in Java
Class | Description (English) | विवरण (Hindi) |
---|---|---|
File | Represents file or directory path | फ़ाइल या डायरेक्टरी का प्रतिनिधित्व करता है |
FileReader | Used to read data from a file character by character | फ़ाइल को कैरेक्टर-बाय-कैरेक्टर पढ़ने के लिए |
FileWriter | Used to write character data to a file | फ़ाइल में कैरेक्टर डेटा लिखने के लिए |
BufferedReader | Reads text efficiently line by line | टेक्स्ट को लाइन-बाय-लाइन प्रभावी रूप से पढ़ता है |
BufferedWriter | Writes text efficiently to a file | टेक्स्ट को प्रभावी रूप से फ़ाइल में लिखता है |
FileInputStream | Reads binary data from a file | बाइनरी डेटा को फ़ाइल से पढ़ने के लिए |
FileOutputStream | Writes binary data to a file | बाइनरी डेटा को फ़ाइल में लिखने के लिए |
1️⃣ Creating a File (फ़ाइल बनाना)
import java.io.File;
import java.io.IOException;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 (आउटपुट):
-
File created: myfile.txt
-
If file already exists → File already exists.
2️⃣ Writing to a File (फ़ाइल में लिखना)
import java.io.FileWriter;
import java.io.IOException;class WriteFileExample {public static void main(String[] args) {try {FileWriter writer = new FileWriter("myfile.txt");writer.write("Hello, this is Java File Handling!");writer.close();System.out.println("Successfully wrote to the file.");} catch (IOException e) {System.out.println("An error occurred.");e.printStackTrace();}}}
3️⃣ Reading from a File (फ़ाइल से पढ़ना)
import java.io.File;
import java.io.FileNotFoundException;import java.util.Scanner;class ReadFileExample {public static void main(String[] args) {try {File file = new File("myfile.txt");Scanner reader = new Scanner(file);while (reader.hasNextLine()) {String data = reader.nextLine();System.out.println(data);}reader.close();} catch (FileNotFoundException e) {System.out.println("File not found.");e.printStackTrace();}}}
4️⃣ Deleting a File (फ़ाइल को हटाना)
import java.io.File;
class DeleteFileExample {public static void main(String[] args) {File file = new File("myfile.txt");if (file.delete()) {System.out.println("Deleted the file: " + file.getName());} else {System.out.println("Failed to delete the file.");}}}
✅ Key Points (मुख्य बातें)
-
File Handling is essential for persistent storage.
-
Use FileReader/FileWriter for text data.
-
Use FileInputStream/FileOutputStream for binary data.
-
Always close file objects to avoid data loss.
-
Use try-catch blocks to handle exceptions.
Comments
Post a Comment