Writing Files

Although we have been able to make use of data stored in files (in the Files tutorial), we have not yet managed to store modified data back to disk, which leaves our applications lacking functionality. Furtunately Java makes it relatively easy to save arrays of items to a file on disk, we just need to make use of a few packages which provide the classes we need. To use the example code below, you would first need to add the following import statements:

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.Charset;
import java.nio.file.Files;
If you note that a number of the imports reside within java.nio.file, we could simplify the import statement to include all packages in that namespace as follows:
import java.nio.charset.Charset;
import java.nio.file.*;

A method to write an ArrayList object looks like this - note the use of try/catch:

private static void arrayListToFile(ArrayList<String> arrayList){
    Path location = Paths.get("src/mytextdata.txt");
    Charset utf8 = Charset.forName("UTF-8");
    try {
        Files.write(location, arrayList, utf8);
    catch (IOException e){
        System.out.println("The file could not be saved");
The above method writes a text file. In order the code is written it:
  1. Creates a Path object to refer to the location of the file we want to write to (The file does not have to exist prior to the execution of the code, but any folders referenced in the path do)
  2. Determines which character set we will use when writing the file (in this case the very commonly used UTF-8 charset)
  3. Attempts to write, at the location specified, the contents of the arrayList object, using the utf8 encoding. If a file pre-exists at this location it will be overwritten.
  4. Outputs an error to the console if it does not work


Modify the programme you created in the first task for in the File Input tutorial (reading names from list), so that the user can add more names to the list, and then save that file back to disk, such that the names persist when you next launch the programme


Modify the zoo names task programme so that it loads from and writes to file.

Research task

Sometimes we may want to use alternative options for saving files (such as appending a file, or failing if we are expecting to create a file and one already exists). Find out how to configure the behaviour of the Files.write() method to handle such scenarios.