Java reading a file into an ArrayList?

Java

Java Problem Overview


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

Here are the file contents:

cat
house
dog
.
.
.

Just read each word into the ArrayList.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

You can use:

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

Source: Java API 7.0

Solution 3 - Java

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"));

Solution 4 - Java

Simplest form I ever found is...

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));

Solution 5 - Java

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;
}

Solution 6 - Java

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();

Solution 7 - Java

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();
    }
}

Solution 8 - Java

//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;
}

Solution 9 - Java

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]+")
);

Solution 10 - Java

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.

Solution 11 - Java

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;
	}
}

Solution 12 - Java

    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 */

Solution 13 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser618712View Question on Stackoverflow
Solution 1 - JavaAhmed KotbView Answer on Stackoverflow
Solution 2 - JavaGerman AttanasioView Answer on Stackoverflow
Solution 3 - JavaBozhoView Answer on Stackoverflow
Solution 4 - JavaKhanView Answer on Stackoverflow
Solution 5 - JavaKrisView Answer on Stackoverflow
Solution 6 - JavaWhiteFang34View Answer on Stackoverflow
Solution 7 - JavalukastymoView Answer on Stackoverflow
Solution 8 - JavagkikoView Answer on Stackoverflow
Solution 9 - JavaVivin PaliathView Answer on Stackoverflow
Solution 10 - JavaLarsView Answer on Stackoverflow
Solution 11 - JavaEric LeschinskiView Answer on Stackoverflow
Solution 12 - JavaPrabhakar Kumar OjhaView Answer on Stackoverflow
Solution 13 - JavacharuView Answer on Stackoverflow