Writing to a File

The example below creates an array of Strings and then passes that array to a method that prints the contents of the array to a file.

import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

public class Driver {
    public static void main(String[] args) {
        String[] words = {"Hello", "world!"}; 

        writeSections("strings.txt", words);
    }

    private static void writeSections(String filename, String[] data) {
        PrintWriter writer;
        try {
            writer = new PrintWriter(filename, "UTF-8");
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }

        for(int i = 0; i < data.length; i++) {
            writer.println(data[i]);
        }
        writer.close();
    }
}

© 2017 – 2019, Eric. All rights reserved.