Commit 7ab1469
committed
feat: write string data to file using FileOutputStream (Demo5)
WHAT:
- Implemented a program that demonstrates how to write an entire string
into a file using `FileOutputStream`.
- File used: Demo5.txt
HOW:
1. Created a `FileOutputStream` pointing to Demo5.txt.
2. Defined a string: "converting string into byte array".
3. Converted the string into a byte array via `getBytes()`.
4. Wrote the byte array to the file using `fout.write(b)`.
5. Closed the stream to free system resources.
6. Printed "success" on successful write.
KEY POINTS:
- `FileOutputStream` works with bytes, so strings must be converted into
byte arrays (`String.getBytes()`).
- Closing the stream is essential to avoid resource leaks and flush data
to disk.
- By default, opening a file with `FileOutputStream` overwrites existing
content.
REAL-WORLD USE CASES:
- Persisting string-based data (logs, user input, configuration).
- Writing data from memory into a plain text file.
- Base building block for advanced file writing (e.g., buffered streams,
file writers).
- Converting any string to bytes and saving in binary files (beyond just
text).
NOTES:
- To append instead of overwrite, use:
`new FileOutputStream(path, true)`.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 61e20de commit 7ab1469
File tree
2 files changed
+14
-14
lines changed- Section23JavaIOStreams/DemoCodes
- TXT Files
- src
2 files changed
+14
-14
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
| 1 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
11 | 11 | | |
12 | 12 | | |
| 13 | + | |
13 | 14 | | |
14 | 15 | | |
15 | | - | |
16 | | - | |
| 16 | + | |
17 | 17 | | |
18 | 18 | | |
19 | 19 | | |
20 | 20 | | |
| 21 | + | |
21 | 22 | | |
22 | 23 | | |
23 | 24 | | |
24 | 25 | | |
25 | 26 | | |
26 | | - | |
27 | | - | |
| 27 | + | |
28 | 28 | | |
0 commit comments