Commit 2758311
committed
feat: add FileInputStream demo to read file byte by byte
WHAT:
- Implemented a simple file I/O example using `FileInputStream`.
- Opened `Demo1.txt` and read data one byte at a time.
- Printed each byte as a character to the console.
- Ensured proper resource cleanup by explicitly calling `fin.close()`.
- Wrapped in try-catch to handle file not found and I/O errors gracefully.
KEY LEARNINGS:
1. FileInputStream
- A byte stream for reading raw bytes from a file.
- Works for both text and binary data (images, audio, video).
- `fin.read()` → returns an int [0–255] or -1 (EOF).
2. Conversion and Loop
- `(char)i` converts numeric byte value to character for printing.
- While loop continues until EOF is reached (-1).
3. Exception Handling
- Prevents crashes if file path is wrong or I/O issues occur.
- Closing stream (`fin.close()`) is essential to free system resources.
4. Best Practices
- Prefer `try-with-resources` (Java 7+) → auto-closes file stream.
- Use `FileReader`/`BufferedReader` for text files (encoding-aware).
- Use `FileInputStream` for binary files (e.g., PDFs, images).
REAL-LIFE APPLICATIONS:
- Reading configuration or log files.
- Streaming binary data (images, audio, video).
- Implementing custom parsers for protocols or file formats.
- Low-level utilities (e.g., checksum calculators, file encryption).
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 762312f commit 2758311
File tree
2 files changed
+44
-18
lines changed- Section23JavaIOStreams/DemoCodes
- TXT Files
- src
2 files changed
+44
-18
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 | | - | |
| 2 | + | |
4 | 3 | | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
9 | 7 | | |
10 | | - | |
11 | | - | |
| 8 | + | |
| 9 | + | |
12 | 10 | | |
13 | 11 | | |
14 | | - | |
15 | | - | |
16 | | - | |
17 | | - | |
18 | | - | |
19 | | - | |
20 | | - | |
21 | 12 | | |
22 | 13 | | |
23 | | - | |
24 | | - | |
| 14 | + | |
25 | 15 | | |
26 | 16 | | |
27 | 17 | | |
28 | 18 | | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 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 | + | |
0 commit comments