Commit 01d0c52
committed
feat: add FileExample4 to demonstrate reading files with FileReader (character stream)
WHAT:
- Implemented FileExample4 to show how to read text files using FileReader instead of FileInputStream.
- Used try-with-resources for automatic resource management.
- Read the file character by character until end-of-file (`-1`) and printed the output.
WHY:
- FileReader is a character stream, making it more suitable for reading text files compared to byte streams.
- Automatically handles character decoding based on the platform’s default charset.
- Provides a simpler approach for text data compared to manually casting bytes from FileInputStream.
HOW:
1. Opened the file `WithResources.txt` using FileReader inside try-with-resources.
2. Used `fr.read()` to read one character at a time.
3. Printed each character to the console until EOF was reached.
BENEFITS:
- Demonstrates character-based file reading in Java.
- Simplifies handling of text files without manual byte-to-char conversion.
- Ensures proper resource cleanup using try-with-resources.
REAL-WORLD APPLICATIONS:
- Reading configuration files, logs, or structured text data.
- Building simple text processing tools where character decoding is automatically managed.
- Useful in situations where only text files (not binary data) are processed.
NOTES:
- For larger files, `BufferedReader` should be preferred over FileReader alone for efficiency.
- Default charset is platform-dependent; for consistent cross-platform behavior, use `InputStreamReader` with explicit charset.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent f9d213a commit 01d0c52
1 file changed
+35
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
6 | | - | |
| 5 | + | |
| 6 | + | |
7 | 7 | | |
8 | 8 | | |
9 | | - | |
10 | | - | |
| 9 | + | |
11 | 10 | | |
12 | 11 | | |
13 | 12 | | |
14 | 13 | | |
15 | | - | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 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 | + | |
0 commit comments