Skip to content

Commit

Permalink
Add create dir if it does not exist
Browse files Browse the repository at this point in the history
Write to file would throw error if the dir does not exist.

The program would now create a new dir and file if it does not exist
  • Loading branch information
peter-yeh committed Aug 23, 2020
1 parent 1e2164a commit 2a6ca37
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/main/java/duke/utils/DukeFileHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ public List<Task> readFile() throws FileNotFoundException {
File file = new File(path);

if (!file.exists()) {
try {
// todo find out why access is denied when creating file
file.mkdirs();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return new ArrayList<>();

} else {
Expand Down Expand Up @@ -60,17 +67,22 @@ private Task createTask(String input) {
}


// todo the access denied to write file
public void writeToFile(List<Task> list) throws IOException {
FileWriter fileWriter = new FileWriter(path);
StringBuilder content = new StringBuilder();

for (Task task : list) {
content.append(task.toCustomString()).append(System.lineSeparator());
}
try {
FileWriter fileWriter = new FileWriter(path);
StringBuilder content = new StringBuilder();
for (Task task : list) {
content.append(task.toCustomString()).append(System.lineSeparator());
}

fileWriter.write(content.toString());
fileWriter.close();

fileWriter.write(content.toString());
fileWriter.close();
} catch (IOException e) {
// e.printStackTrace();
}
}

}

0 comments on commit 2a6ca37

Please sign in to comment.