Reading Text Files into String Arrays in Java

Some example Java code to read the contents of text file into a string array, line-by-line. Here is the Java class which is used to output the string array after the file location has been passed to it:

// ReadFile.java
package javareadtextfile;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadFile 
{
    public String[] readLines(String filename) throws IOException 
    {
        FileReader fileReader = new FileReader(filename);
        
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        
        while ((line = bufferedReader.readLine()) != null) 
        {
            lines.add(line);
        }
        
        bufferedReader.close();
        
        return lines.toArray(new String[lines.size()]);
    }   
}

And here is some code showing the actual usage of the ReadFile class. An exception is thrown if the program cannot find the filename passed to it:

package javareadtextfile;
import java.io.IOException;

public class JavaReadTextFile 
{
    public static void main(String[] args) 
    {
        ReadFile rf = new ReadFile();
        
        // The text file location of your choice
        String filename = "c:/dump/Hamlet.txt";
        
        try
        {
            String[] lines = rf.readLines(filename);
        
            for (String line : lines) 
            {
                System.out.println(line);
            }
        }
        catch(IOException e)
        {
            // Print out the exception that occurred
            System.out.println("Unable to create "+filename+": "+e.getMessage());              
        }
    }
}

You might wish to try this with the following piece of text.

Latest Comments

  1. Nelly 17 October 2012
    • Andy 18 October 2012
  2. Rain 27 November 2012
  3. Andy 27 November 2012
  4. Tiara 8 December 2013
    • happyuk 8 December 2013
  5. zack6849 13 April 2014
    • happyuk 13 April 2014
  6. zinat 15 April 2014
  7. Jeremy 10 April 2015
    • happyuk 10 April 2015

Leave a Reply to Nelly Cancel reply