Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 2026)

Previous: HelloFile

LoadStrings

//
// LoadStrings.java
//


// This program demonstrates the implementation of a Processing-style
// loadStrings() function using the Java IO classes File and Scanner.  
//
// The loadStrings() function reads the entire file into memory as an array of
// Strings.


import java.io.*;
import java.util.*;


public class LoadStrings 
{
    public static String[] loadStrings(String filename)
    {
        ArrayList<String> lines = new ArrayList<String>();

        try {
            File f = new File(filename); 
            Scanner s = new Scanner(f);
       
            while (s.hasNext())
            {
                String line = s.nextLine();
                lines.add(line);
            }
        }
        catch (Exception e)
        {
            System.out.println(e);
        }

        String[] result = lines.toArray(new String[0]);
        return result;
    }

    public static void readData(String filename)
    {
        String[] lines = loadStrings(filename);

        for (String line : lines)
            System.out.println(line);

        System.out.println();
    }

    public static void main(String[] args)
    {
        readData("high_scores.txt");
    }
}

Output:

DrKessner 1234
Gadget 2345
Tux 3456

Next: