44import java .io .FileNotFoundException ;
55import java .io .FileWriter ;
66import java .io .IOException ;
7- import java .nio . file . Files ;
8- import java .nio .file . Path ;
7+ import java .net . URLDecoder ;
8+ import java .nio .charset . StandardCharsets ;
99import java .time .LocalDateTime ;
1010import java .util .Scanner ;
1111
12+ import duke .Launcher ;
1213import duke .ui .Parser ;
1314
1415
@@ -22,11 +23,11 @@ public class Storage {
2223 /**
2324 * Initializes a storage/loader with a file path.
2425 *
25- * @param fileName Name of text file in directory data/ from which tasks are loaded, and to which tasks are saved.
26+ * @param fileName Name of text file in directory /data/ from which tasks are loaded,
27+ * and to which tasks are saved.
2628 */
2729 public Storage (String fileName ) {
28- assert Files .isDirectory (Path .of ("data" ));
29- this .filePath = "data/" + fileName ;
30+ this .filePath = this .getSaveFilePath (fileName );
3031 }
3132
3233 /**
@@ -152,4 +153,35 @@ private String convertTaskToSavableString(Task task) {
152153
153154 return taskType + " | " + done + " | " + description + " | " + dateTimeString + "\n " ;
154155 }
156+
157+ /**
158+ * Builds the path to the text file from which to load data and to which to save data.
159+ *
160+ * @param fileName Name of text file.
161+ * @return Path to the save file.
162+ */
163+ private String getSaveFilePath (String fileName ) {
164+ String appDirectory = URLDecoder .decode (
165+ Launcher .class
166+ .getProtectionDomain ()
167+ .getCodeSource ()
168+ .getLocation ()
169+ .getPath (),
170+ StandardCharsets .UTF_8 );
171+
172+ // Obtain the path of the directory containing the save file
173+ String dataDirectory ;
174+ if (appDirectory .endsWith (".jar" )) {
175+ dataDirectory = new File (appDirectory ).getParentFile ().getPath () + "/data" ;
176+ } else {
177+ dataDirectory = "data" ;
178+ }
179+
180+ if (!new File (dataDirectory ).exists ()) {
181+ boolean directoryCreated = new File (dataDirectory ).mkdir ();
182+ assert directoryCreated ;
183+ }
184+
185+ return dataDirectory + "/" + fileName ;
186+ }
155187}
0 commit comments