11package helperbot .ui ;
22
3+ import java .io .File ;
34import java .io .FileNotFoundException ;
45import java .io .IOException ;
6+ import java .nio .file .Path ;
7+ import java .nio .file .Paths ;
58import java .util .Scanner ;
69
710import helperbot .command .Command ;
1619 */
1720public class HelperBot {
1821
22+ private static final String DATA_DIRECTORY = "data" ;
23+ private static final String FILE_NAME = "HelperBot.txt" ;
1924 private final TaskList tasks ;
2025 private final Response response ;
2126 private final Storage storage ;
@@ -31,15 +36,42 @@ public HelperBot(String filePath) {
3136 try {
3237 tasks1 = new TaskList (this .storage .load ());
3338 } catch (FileNotFoundException e ) {
34- this .response .getErrorMessage (filePath + " is not found." );
39+ System . err . println ( this .response .getErrorMessage (filePath + " is not found." ) );
3540 tasks1 = new TaskList ();
3641 } catch (HelperBotFileException e ) {
37- this .response .getErrorMessage (e .toString ());
42+ System . err . println ( this .response .getErrorMessage (e .toString () ));
3843 tasks1 = new TaskList ();
3944 }
4045 this .tasks = tasks1 ;
4146 }
4247
48+ /**
49+ * Create data/HelperBot.txt if it does not exist.
50+ * @throws IOException Error occurs when creating data/HelperBot.txt
51+ */
52+ public static void createFileIfNotExist () throws IOException {
53+ Path currentPath = Paths .get ("." ).toAbsolutePath ();
54+ Path dataPath = currentPath .resolve (DATA_DIRECTORY );
55+ Path filePath = dataPath .resolve (FILE_NAME );
56+
57+ File dataDir = dataPath .toFile ();
58+ File file = filePath .toFile ();
59+
60+ if (!dataDir .exists ()) {
61+ boolean success = dataDir .mkdir ();
62+ if (!success ) {
63+ throw new IOException ("Failed to create the data directory: " + dataDir .getAbsolutePath ());
64+ }
65+ }
66+
67+ if (!file .exists ()) {
68+ boolean success = file .createNewFile ();
69+ if (!success ) {
70+ throw new IOException ("Failed to create the file: " + file .getAbsolutePath ());
71+ }
72+ }
73+ }
74+
4375 /**
4476 * Initializes the chat.
4577 */
@@ -93,14 +125,14 @@ public String greet() {
93125 */
94126 public void saveToFile () {
95127 try {
128+ HelperBot .createFileIfNotExist ();
96129 this .storage .write (this .tasks );
97- response .getExitMessage ();
98130 } catch (IOException e ) {
99- response .getExitErrorMessage (e .toString ());
131+ System . err . println ( this . response .getExitErrorMessage (e .toString () ));
100132 }
101133 }
102134
103135 public static void main (String [] args ) {
104- new HelperBot ("./helperbot/storage/ data/HelperBot.txt" ).chat ();
136+ new HelperBot ("data/HelperBot.txt" ).chat ();
105137 }
106138}
0 commit comments