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();
    }
}

Reading and Writing Files I

Two of the most often used classes for reading and writing files are FileInputStream and FileOutputStream.

When opening files you must use a try-catch block.

public class FileIO {
    public static void main(String[] args) {
        Scanner sc;
        PrintWriter pw;
        try {
            sc = new Scanner(new FileInputStream("in.txt"));
            pw = new PrintWriter(new FileOutputStream("out.txt"));
            String token;
            while (sc.hasNext()){
                token = sc.next();
                pw.println(token);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.toString());
            return;
        }

        sc.close(); 
        pw.close();
    }
}

Reading and Writing Files II

The example below uses a try-with-resources statement. This was added to JDK 7. When implemented this way, you don’t have to explicitly close the streams – Java will do it for you when they are garbage collected.

import java.io.FileInputStream;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class FileIO {
    public static void main(String[] args) {

        try (Scanner sc = new Scanner(new FileInputStream("in.txt"));
            PrintWriter pw = new PrintWriter(new FileOutputStream("out.txt"))) 
        {

            String token;
            while (sc.hasNext()){
                token = sc.next();
                pw.println(token);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.toString());
            return;
        } 
    }
}

Parsing Strings

Parsing is the process of splitting a string into smaller substrings (a.k.a. tokens).

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * Changing the delimiter on the Scanner.
 */
public static void parseColonDelin(Scanner sc) {
    sc.useDelimiter(":|\n");
    while(sc.hasNext()) {
        String token = sc.next();
        System.out.println("[" + token + "]");
    }
}

/*
 * Reading each line of input as a String, splitting the String, 
 * and putting the tokens in an array.
 */
public static void parseTabDelin(Scanner sc) {
    if (!sc.hasNext())
        return;
 
    while(sc.hasNext()) {
        String input = sc.nextLine();
        String[] tokens = input.split("\t|\n");
        for(String token : tokens)
            System.out.println("[" + token + "]");
    }
}

/*
 * Reading each line as a String, creating a regex Pattern,
 * and using a Matcher to find instances of the pattern in 
 * the String.
 */
public static void parseFixedLen(Scanner sc) {
    if (!sc.hasNext())
        return;

    while(sc.hasNext()) {
        String input = sc.nextLine();
        Pattern p = Pattern.compile("[PKHT]\\d\\d");
        Matcher m = p.matcher(input);
        while (m.find()) {
            String token = m.group();
            System.out.println("[" + token + "]");
        }
    }
}