Skip to content

Commit 484dd16

Browse files
committed
refactor: add try-with-resources for safer file writing with FileOutputStream
WHAT: - Implemented `FileExample2` demonstrating file writing using `FileOutputStream` inside a try-with-resources block. - Wrote a string ("With Using Resources.") to a file after converting it into a byte array. - Replaced manual `fos.close()` with automatic resource management. - Included commented alternatives: - Writing each byte individually in a loop. - Writing partial content using `fos.write(byte[], offset, length)`. WHY: - Ensures automatic closing of the stream, reducing the risk of resource leaks. - Simplifies error handling and makes the code cleaner. - Encourages best practices in modern Java (Java 7+). HOW: 1. Opened file using `try(FileOutputStream fos = new FileOutputStream(path)) { ... }`. 2. Converted string to bytes (`str.getBytes()`). 3. Wrote the byte array directly with `fos.write(b)`. 4. Stream automatically closed at the end of the try block. BENEFITS: - No need for explicit `close()` calls. - Even if an exception occurs, the resource will be closed properly. - Cleaner, more concise code compared to manual try-catch-finally. REAL-WORLD USE CASES: - Writing logs, reports, or configuration files. - Safely handling file I/O in enterprise applications where resource leaks can be costly. - Recommended for modern Java development wherever streams are used. NOTES: - Multiple resources (e.g., FileInputStream + BufferedInputStream) can be opened in the same try-with-resources block. - For text-heavy operations, `FileWriter`/`BufferedWriter` may be preferable. - For performance with large data, combine with `BufferedOutputStream`. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 6df6bce commit 484dd16

File tree

2 files changed

+48
-14
lines changed

2 files changed

+48
-14
lines changed
Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,68 @@
11
import java.io.*;
22

33
public class FileExample2 {
4-
5-
public static void main(String[] args) throws Exception
6-
{
7-
8-
try(FileOutputStream fos=new FileOutputStream("C://Users//somes//Downloads//JAVA SE//Section23JavaIOStreams//src//MyJAVA/WithResources.txt");)
4+
public static void main(String[] args) throws Exception {
5+
try(FileOutputStream fos=new FileOutputStream("/Users/somesh/Java SE/JavaEvolution-Learning-Growing-Mastering/Section23JavaIOStreams/src/MyJAVA/WithResources.txt");)
96
{
10-
String str="With Using Resources";
11-
7+
String str = "With Using Resources.";
128
byte b[]=str.getBytes();
139

1410
/*
1511
//fos.write(str.getBytes());
12+
1613
for(byte x:b)
17-
fos.write(x);*/
14+
fos.write(x);
15+
*/
1816
//fos.write(b, 6, str.length()-6);
19-
2017
fos.write(b);
21-
2218
//fos.close();
23-
2419
}
20+
2521
/*catch(FileNotFoundException e)
2622
{
2723
System.out.println(e);
2824
}
2925
catch(IOException e)
3026
{
3127
System.out.println(e);
32-
}*/
28+
}
29+
*/
3330
}
34-
}
31+
}
32+
33+
/*
34+
1. try-with-resources:
35+
- Java feature jisme try block ke andar declare kiya gaya resource
36+
(jaise FileOutputStream) automatically close ho jaata hai.
37+
- `fos.close()` likhne ki zaroorat nahi hoti, JVM khud handle kar leti hai.
38+
- Safer aur clean code likhne ke liye prefer karte hain.
39+
40+
2. FileOutputStream:
41+
- Stream jo file ke andar data write karne ke liye use hota hai.
42+
- Data binary form me likhta hai (String ko bhi bytes me convert karna padta hai).
43+
- Agar file exist nahi hai → nayi file create ho jaati hai.
44+
- Agar file already exist hai → purana content overwrite ho jaata hai.
45+
46+
3. Important Methods:
47+
- fos.write(int b) → ek single byte likhta hai.
48+
- fos.write(byte[] b) → pura byte array likhta hai.
49+
- fos.write(byte[] b, int off, int len) → array ke ek specific portion ko write karta hai.
50+
- fos.close() → normally zaroori hota hai, par yaha auto-close ho gaya (try-with-resources).
51+
52+
4. is program me kya ho raha hai:
53+
- `FileOutputStream fos = new FileOutputStream(".../WithResources.txt");`
54+
→ File ko open/create kiya writing ke liye.
55+
- `str.getBytes()` → String ko byte array me convert kiya.
56+
- `fos.write(b);` → pura string file me write kiya.
57+
- Stream auto-close ho gaya because of try-with-resources.
58+
59+
5. Use Cases:
60+
- Text ya binary file banani ho.
61+
- Logs, reports ya raw byte data likhne ke liye.
62+
- Agar sirf characters write karne ho toh `FileWriter` ka use karna better.
63+
64+
✔ try-with-resources = auto close, no need for finally block.
65+
✔ FileOutputStream = binary write stream.
66+
✔ getBytes() = String → byte array conversion.
67+
✔ Overwrites file by default (append karna ho toh `new FileOutputStream(path, true)` use karo).
68+
*/
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
With Using Resources
1+
With Using Resources.

0 commit comments

Comments
 (0)