Commit 6df6bce
committed
feat: implement basic file writing example using FileOutputStream
WHAT:
- Added `FileExample` to demonstrate writing data into a file using `FileOutputStream`.
- Writes a full string directly to a file using `fos.write(str.getBytes())`.
- Included commented alternatives:
- Writing bytes one-by-one in a loop.
- Writing a substring portion using `fos.write(byte[], offset, length)`.
WHY:
- `FileOutputStream` is one of the core classes in Java I/O for writing raw bytes into files.
- Understanding byte-level writing is important before working with higher-level abstractions like `BufferedWriter` or `PrintWriter`.
HOW:
1. Opened a file at the given path (`Test.txt`) using `FileOutputStream`.
2. Converted a string into a byte array with `getBytes()`.
3. Wrote the byte array to the file in one go.
4. Closed the stream to release system resources.
ERROR HANDLING:
- Caught `FileNotFoundException` (e.g., if the path is invalid).
- Caught general `IOException` for any unexpected I/O issues.
REAL-WORLD USE CASES:
- Writing logs or reports directly into a file.
- Saving application data (text or binary) at runtime.
- Building utilities that generate configuration or result files.
- Basis for advanced file operations (serialization, buffering, streaming large datasets).
NOTES:
- Always close the stream (`fos.close()`) to avoid resource leaks.
- Better approach: use try-with-resources (`try(FileOutputStream fos = ...) { ... }`) for auto-closing.
- For character-specific writing, `FileWriter` or `BufferedWriter` is more convenient.
- For frequent writes, consider `BufferedOutputStream` for performance improvements.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 76b0f29 commit 6df6bce
2 files changed
+35
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
4 | 4 | | |
5 | 5 | | |
6 | 6 | | |
7 | | - | |
8 | | - | |
| 7 | + | |
| 8 | + | |
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
| |||
25 | 25 | | |
26 | 26 | | |
27 | 27 | | |
28 | | - | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
| 1 | + | |
0 commit comments