एक नोट लिखना और पढ़ना
अब जबकि आप फ़ाइलें बना सकते हैं, तो आइए असली कंटेंट जोड़ें. आप एक छोटा नोट एक टेक्स्ट फ़ाइल में लिखेंगे और फिर उसे पढ़कर जाँचेंगे कि वह सही से सेव हुआ है. यह किसी भी नोट-टेकिंग एप्लिकेशन की मुख्य क्षमता होती है.
java.io से सभी ज़रूरी पैकेज आपके लिए इम्पोर्ट कर दिए गए हैं.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Java में इनपुट/आउटपुट और स्ट्रीम्स
अभ्यास निर्देश
- टेक्स्ट
"Start from the beginning"को"note.txt"नाम की फ़ाइल में लिखें. "note.txt"के लिएappendमोड में एकFileWriterबनाएँ और उसेfwAppendModeनाम दें.- फ़ाइल की मौजूदा सामग्री को ओवरराइट किए बिना टेक्स्ट
" Add to the end"जोड़ें. - फ़ाइल की सामग्री पढ़ने के लिए
FileReaderका उपयोग करें और उसे कंसोल पर एक-एक करेक्टर करके दिखाएँ.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
class FileReadWrite {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("note.txt");
// Write "Start from the beginning" to the file
fw.____("Start from the beginning");
fw.close();
// Create a FileWriter in append mode
FileWriter fwAppendMode = new ____("note.txt", ____);
// Add " Add to the end" to the end of file
fwAppendMode.____(" Add to the end");
fwAppendMode.close();
FileReader fr = new FileReader("note.txt");
int character;
// Read the file content character by character
while ((character = fr.____()) != -1) {
System.out.print((char) character);
}
fr.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}