-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotesApp.java
More file actions
88 lines (74 loc) · 2.92 KB
/
Copy pathNotesApp.java
File metadata and controls
88 lines (74 loc) · 2.92 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
78
79
80
81
82
83
84
85
86
87
88
package JavaNotesApp;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class NotesApp {
private static final String FILE_NAME = "JavaNotesApp/notes.txt";
private static Scanner sc = new Scanner(System.in);
private static void addNote() {
System.out.println("Enter your note (type 'END' on a new line to finish): ");
StringBuilder note = new StringBuilder();
String line;
while (!(line = sc.nextLine()).trim().equals("END")) {
note.append(line).append(System.lineSeparator());
}
try (FileWriter writer = new FileWriter(FILE_NAME, true)) {
writer.write(note.toString());
System.out.println("Note added successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to file!");
e.printStackTrace();
}
}
private static void viewNotes() {
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
System.out.println("--- Your Notes ---");
while ((line = reader.readLine()) != null) {
System.out.println(" - " + line);
}
} catch (FileNotFoundException e) {
System.out.println("No notes found. add some first!");
} catch (IOException e) {
System.out.println("An error occurred while reading the file!");
e.printStackTrace();
}
}
public static void main(String[] args) {
boolean exit = false;
System.out.println("<--- Java File I/O - Notes App --->");
while (!exit) {
System.out.println("Select an option to perform task.");
System.out.println("1. Add Note");
System.out.println("2. View Notes");
System.out.println("3. Exit");
System.out.print("Enter your choice---: ");
if (sc.hasNextInt()) {
int choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1:
addNote();
break;
case 2:
viewNotes();
break;
case 3:
System.out.println("Exiting from the app.");
exit = true;
break;
default:
System.out.println("Invalid choice, Please select a valid option!");
break;
}
System.out.println("-----------------------------------------");
} else {
System.out.println("Invalid input, Please enter a number!");
sc.nextLine();
}
}
}
}