-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotesApp.java
More file actions
77 lines (66 loc) · 2.62 KB
/
Copy pathNotesApp.java
File metadata and controls
77 lines (66 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* NotesApp - A simple beginner-friendly Java application to demonstrate File I/O.
* This app allows writing a note to a text file and reading all notes back.
*
* Author: Mummana Devi Prasad
*/
public class NotesApp {
// The name of the file where notes will be stored
private static final String FILE_NAME = "notes.txt";
/**
* Writes a note to the file.
* Use FileWriter to append the note to the end of the file.
*
* @param note The content of the note to be saved.
*/
public void addNote(String note) {
// Using try-with-resources to ensure the FileWriter is closed automatically
try (FileWriter writer = new FileWriter(FILE_NAME, true)) {
writer.write(note + "\n");
System.out.println("Success: Note added successfully to " + FILE_NAME);
} catch (IOException e) {
System.out.println("Error while writing to file: " + e.getMessage());
}
}
/**
* Reads and displays all notes from the file.
* Uses FileReader wrapped in BufferedReader for efficient reading.
*/
public void readNotes() {
System.out.println("\n--- All Notes ---");
// Using try-with-resources for FileReader and BufferedReader
try (FileReader reader = new FileReader(FILE_NAME);
BufferedReader bufferedReader = new BufferedReader(reader)) {
String line;
boolean hasNotes = false;
// Read the file line by line
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
hasNotes = true;
}
if (!hasNotes) {
System.out.println("No notes found in the file.");
}
} catch (IOException e) {
System.out.println("Error while reading from file: " + e.getMessage() +
" (Maybe the file hasn't been created yet?)");
}
}
/**
* Main method to demonstrate the functionality of the NotesApp.
*/
public static void main(String[] args) {
NotesApp myApp = new NotesApp();
// 1. Adding a sample note
System.out.println("Adding a sample note...");
myApp.addNote("Learning Java File I/O is fun!");
myApp.addNote("Object-Oriented Programming makes code organized.");
// 2. Reading all notes back
System.out.println("\nReading all notes from the file...");
myApp.readNotes();
}
}