
Java Programming
June 15, 2025 at 04:23 PM
📁 *Java File I/O (Input/Output)* 🔄
🧾 *1. Reading Files*
• Using `File` + `Scanner`:
```java
File file = new File("data.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
```
• Using `BufferedReader`:
```java
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
```
📝 *2. Writing to Files*
• Using `FileWriter`:
```java
FileWriter fw = new FileWriter("output.txt");
fw.write("Hello, World!");
fw.close();
```
• Using `BufferedWriter`:
```java
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("This is a new line.");
bw.newLine();
bw.write("Another line.");
bw.close();
```
🔐 *3. Best Practices*
✅ Always close files (`close()` method)
✅ Use `try-with-resources` to auto-close
✅ Handle exceptions (`IOException`)
💡 *Tip:* Try building a mini text editor or log analyzer to practice!
Java Roadmap: https://whatsapp.com/channel/0029VamdH5mHAdNMHMSBwg1s/810
*React ❤️ for more* ✨📂
❤️
👍
❤
♥
😮
🥵
✌
😂
🥶
☕
79