Java: Files & folders

Read a text file into an ArrayList (one entry per line)

package ch.isl.helpers;

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class Files {
    public static ArrayList<String> readFile(String filename) {
        ArrayList<String> content = new ArrayList<String>();
        try {
            File f = new File(filename);
            Scanner reader = new Scanner(f);
            while (reader.hasNextLine()) {
                content.add(reader.nextLine());
            }
            reader.close();
        } catch(Exception e) {
            // This shouldn't be empty, what happens if the filename is misspelt, file has been deleted, permissions problems, etc?
        }
        return content;
    }

    public static void main(String[] args) {
        String fname = "/Users/pbaumgarten/ISL/projects/java/sources.txt";
        ArrayList<String> data = readFile(fname);
        System.out.println(data);
    }
}

Write ArrayList of strings to a text file

package ch.isl.helpers;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Files {
    public static boolean saveFile(String filename, ArrayList<String> content) {
        try {
            FileWriter fw = new FileWriter(filename);
            PrintWriter output = new PrintWriter(fw);
            for (String line: content) {
                output.println( line );
            }
            output.close();
            fw.close();
            return true;
        } catch(Exception e) {
            return false;   // error occurred in saving file
        }
    }

    public static void main(String[] args) {
        // Create the dummy data to save to our file
        ArrayList<String> data = new ArrayList<String>();
        data.add("first");
        data.add("second");
        data.add("third");
        data.add("forth");
        data.add("fifth");
        // Save to file
        String fname = "/Users/pbaumgarten/ISL/projects/java/test-file-save.txt";
        boolean ok = saveFile(fname, data);
    }
}

Folder walk

// From: https://stackoverflow.com/a/2056326
package ch.isl.helpers;
import java.io.File;

public class Files {

    public static void walk( String path ) {
        File root = new File( path );
        File[] list = root.listFiles();
        if (list == null) return;
        for ( File f : list ) {
            if ( f.isDirectory() ) {
                System.out.println( "Dir:" + f.getAbsoluteFile() );
                walk( f.getAbsolutePath() );
            }
            else {
                System.out.println( "File:" + f.getAbsoluteFile() );
            }
        }
    }

    public static void main(String[] args) {
        walk("c:\\" );
    }
}

Other ways of implementing this are discussed at: