0

I have a file in the project in netbeans called "input.txt" which has a list of names like the following:

John Doe
Magnus Carlsen
Mikhail Tal
Bobby Fischer

I created an arraylist with:

ArrayList <String> names = new ArrayList<String>();

I want to add in the arraylist names. I want the value at [0] to be "John Doe" and the value at [1] to be "Magnus Carlsen" and so on. How can I do this?

3 Answers3

1

Java 8

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

javadoc

Java 7

List<String> names = Files.readAllLines(Paths.get("C:/path/To/Your/File.txt"), Charset.defaultCharset());

javadoc

Matthew Madson
  • 1,643
  • 13
  • 24
1

This is somehow trivial:

List<String> names = new ArrayList<>();

try(BufferedReader reader = new BufferedReader(new FileReader("myFile.txt"))) {
    String line;
    while((line = reader.readLine()) != null) {
        names.add(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

System.out.println("My list: " + names);
morgano
  • 17,210
  • 10
  • 45
  • 56
0

You could do something like this:

Scanner s = new Scanner(new File("filePath"));
List<String> names = new ArrayList<String>();

while (s.hasNext()){
    names.add(s.nextLine());
}

s.close()
Josh Roberts
  • 862
  • 6
  • 12