Java File Handling
In Java, files are used to store and manage data permanently on the computer's storage (like your hard disk).
Just like you save a document on your computer, Java programs can create, read, write, and delete files using built-in classes.
Why Use Files in Java?
Permanent Storage: Variables store data temporarily in memory (RAM). But files save data permanently on disk.
Data Sharing: You can save data to a file and read it later or send it to others.
Input/Output: Files allow you to do input/output operations like saving user data, reading configuration, logging errors, and creating reports.
Java में files का use permanently data को computer के storage (जैसे hard disk) में save करने के लिए किया जाता है।
जैसे आप computer पर document save करते हैं, वैसे ही Java program भी files को create, read, write और delete कर सकते हैं।
Java में Files क्यों इस्तेमाल करें?
Permanent Storage: Variables सिर्फ memory (RAM) में temporary data store करते हैं, जबकि files उसे disk पर permanently save करती हैं।
Data Sharing: आप file में data save करके बाद में पढ़ सकते हैं या किसी और को भेज सकते हैं।
Input/Output: User data को save करना, configuration read करना, errors को log करना, reports बनाना — ये सब files से संभव है।
Java's File Handling Classes
Java provides file handling via the java.io
package. Important classes include:
File
FileWriter
FileReader
BufferedReader
Java में file handling के लिए java.io
package दिया गया है। मुख्य classes हैं:
File
FileWriter
FileReader
BufferedReader
Example: Create a File in Java
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
File file = new File("data.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: data.txt
This program uses java.io.File
class to create a new file named data.txt
.
यह प्रोग्राम java.io.File
class का उपयोग करके data.txt
नाम की file बनाता है।