How to Read a File into a List in Java


In this example, we will obtain the methods to read a file into a list.

Source Code

package com.beginner.examples;

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

public class File2ListExample { 
	public static void main(String[] args )
    {	
		String path = "example.txt";
		String line = "";
		List result = new ArrayList();
		BufferedReader br = null;
		FileReader reader = null;
        try
        {
        	// read the file
        	reader = new FileReader(path);
    		br = new BufferedReader(reader);
    		while ((line = br.readLine()) != null) 
    		{
    			result.add(line);
    		}
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        finally 
        {
			try 
			{
				if (br != null) br.close();
				if (reader != null)	reader.close();
			} 
			catch (IOException ex) 
			{
				ex.printStackTrace();
			}
        };
        //print the list
        result.forEach(System.out::println);
    }
}

Output:

test
read

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments