Last active
February 19, 2018 16:49
-
-
Save lucasmelin/6c39c1b661ee9bb7b8fe9fe4eb346aac to your computer and use it in GitHub Desktop.
Save tasks to a file using FileWriter and an enhanced for-loop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Saves tasks found in the ArrayList to a file. | |
* <p> | |
* Each task is separated by a newline, | |
* and the tasks are formatted using the createTabRecord method, which separates the values | |
* of the task with tab characters. This method also overwrites any previous files of the | |
* same name. | |
*/ | |
private void saveTasks(){ | |
if (tasks.isEmpty()){ // Make sure tasks ArrayList isn't empty | |
System.out.print("There are no tasks to save"); | |
} | |
else{ | |
FileWriter taskList = null; | |
int numberOfTasks = 0; | |
try { | |
taskList = new FileWriter("tasks.txt"); | |
for(Task t:tasks){ | |
taskList.append(t.createTabRecord()); | |
taskList.append('\n'); | |
numberOfTasks ++; | |
} | |
System.out.print("Saved "+numberOfTasks+" to file "+System.getProperty("user.dir")+"\tasks.txt"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
finally { | |
if (taskList != null){ // Only try to close the stream if taskList was created | |
try { | |
taskList.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment