77

How do you read the contents of a file into an ArrayList<String> in Java?

Here are the file contents:

cat
house
dog
.
.
.
cb4
  • 6,689
  • 7
  • 45
  • 57
user618712
  • 1,463
  • 7
  • 17
  • 19

13 Answers13

136

This Java code reads in each word and puts it into the ArrayList:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
    list.add(s.next());
}
s.close();

Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Ahmed Kotb
  • 6,269
  • 6
  • 33
  • 52
  • 4
    Oh nice, shorter with `Scanner` than `BufferedReader` and no exceptions to deal with. I guess I'm used to using `BufferedReader` prior to Java 5 when `Scanner` didn't exist, although I've been using Java 5 and 6 for many years. The Commons IO library of course provides the shortest answer if available as others have mentioned, so I generally use that now. – WhiteFang34 Mar 17 '11 at 18:57
  • 9
    Don't you need to specify the delimiter for the scanner, as the default delimiter matches whitespace? i.e. new Scanner(new File("filepath")).useDelimiter("\n"); – Hedley Feb 08 '13 at 16:53
  • @Hedley from java7 on `new Scanner(new File("filepath")).useDelimiter(System.lineSeparator())` because it can differ per OS – Tschallacka Jan 31 '17 at 15:39
62

You can use:

List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );

Source: Java API 7.0

German Attanasio
  • 22,217
  • 7
  • 47
  • 63
50

A one-liner with commons-io:

List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");

The same with guava:

List<String> lines = 
     Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
30

Simplest form I ever found is...

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
User
  • 4,023
  • 4
  • 37
  • 63
11

In Java 8 you could use streams and Files.lines:

List<String> list = null;
try (Stream<String> lines = Files.lines(myPathToTheFile))) {
    list = lines.collect(Collectors.toList());
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}

Or as a function including loading the file from the file system:

private List<String> loadFile() {
    List<String> list = null;
    URI uri = null;

    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }

    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}
Kris
  • 4,595
  • 7
  • 32
  • 50
  • 1
    `List lines = Files.lines(Paths.get("./input.txt")).collect(Collectors.toList());` –  Jun 18 '17 at 10:01
6
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
    words.add(line);
}
reader.close();
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
2

You can for example do this in this way (full code with exceptions handlig):

BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {   
    in = new BufferedReader(new FileReader("myfile.txt"));
    String str;
    while ((str = in.readLine()) != null) {
        myList.add(str);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (in != null) {
        in.close();
    }
}
lukastymo
  • 26,145
  • 14
  • 53
  • 66
1
//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
    List<String> wives = new ArrayList<String>();
    try {
        BufferedReader input = new BufferedReader(new FileReader(fileName));
        // for each line
        for(String line = input.readLine(); line != null; line = input.readLine()) {
            wives.add(line);
        }
        input.close();
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(1);
        return null;
    }
    return wives;
}
gkiko
  • 2,283
  • 3
  • 30
  • 50
1

Here's a solution that has worked pretty well for me:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
);

If you don't want empty lines, you can also do:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
);
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
1

To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.

If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms

The Scanner is much slower. Took me ~138ms

The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.

Lars
  • 3,576
  • 2
  • 15
  • 13
0

Here is an entire program example:

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

public class X {
    public static void main(String[] args) {
    File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
        try{
            ArrayList<String> lines = get_arraylist_from_file(f);
            for(int x = 0; x < lines.size(); x++){
                System.out.println(lines.get(x));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("done");

    }
    public static ArrayList<String> get_arraylist_from_file(File f) 
        throws FileNotFoundException {
        Scanner s;
        ArrayList<String> list = new ArrayList<String>();
        s = new Scanner(f);
        while (s.hasNext()) {
            list.add(s.next());
        }
        s.close();
        return list;
    }
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
0
    Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/

    enter code here

ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/

while (scr.hasNext()){

list.add(scr.next()); } /*above code is responsible for adding data in arraylist with the help of add function */

-4

Add this code to sort the data in text file. Collections.sort(list);

Peter
  • 1,655
  • 22
  • 44
charu
  • 9
  • 2
  • Generally, answers are much more useful if they include an explanation of what the code is intended to do. – Peter Jun 30 '17 at 11:44