From 72cc8d73e5e8955ff1406d58c393ece8c9c0751f Mon Sep 17 00:00:00 2001 From: YaxinWan Date: Thu, 3 Mar 2022 20:59:54 +0800 Subject: [PATCH] Add case when file does not exist. --- src/main/java/Storage.java | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/main/java/Storage.java b/src/main/java/Storage.java index 9eda2bf3d..02844159d 100644 --- a/src/main/java/Storage.java +++ b/src/main/java/Storage.java @@ -3,10 +3,9 @@ import DukeTask.Task; import DukeTask.ToDo; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; public class Storage { /** @@ -39,6 +38,12 @@ public void saveData() throws IOException { * @throws IOException if the file/ file path does not exist. */ public void readData() throws IOException { + try{ + BufferedReader in = new BufferedReader(new FileReader(".\\src\\DataSrc\\taskList.txt")); + } catch(IOException e){ + System.out.println("Welcome new user!"); + createFile("./src/DataSrc"); + } BufferedReader in = new BufferedReader(new FileReader(".\\src\\DataSrc\\taskList.txt")); String taskLine; while ((taskLine = in.readLine()) != null) { @@ -63,4 +68,16 @@ public void readData() throws IOException { in.close(); } + private void createFile(String path){ + try { + File f = new File(path); + if(!f.exists()){ + f.mkdirs(); + } + Files.createFile(Paths.get("./src/DataSrc/taskList.txt")); + System.out.println("File created successfully!"); + }catch(IOException e){ + System.out.println("File created unsuccessfully!"); + } + } }