How do you read the contents of a file into an ArrayList
in Java?
Here are the file contents:
cat
ho
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 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 get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList list = new ArrayList();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}
}