How do you read the contents of a file into an ArrayList
in Java?
Here are the file contents:
cat
ho
You can use:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
Source: Java API 7.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;
}
}
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();
}
}
//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;
}
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.
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;
}