Reading Text Files into String Arrays in Java

Programming Tip:

Now you can load your essential programming tools such as emulators and IDE`s into the cloud with high performance citrix vdi from CloudDesktopOnline and access it remotely at your convenience on your preferred device(PC/Mac/android/iOS). If you prefer a gpu dedicated server, Try dedicated gpu hosting from Apps4Rent with 24*7*365 days top-notch tech-support and migration assistance.

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.

`