-1

I have a text file that contains names followed by .xml such as georgeeliot.xml I then took the text file and placed it into a string. I am now trying to figure out how to loop through the string and place each name.xml into a ArrayList that I created ArrayList<String> items = new ArrayList<String>();

I've done some research, but most examples I can find put them into an array. Thanks for your help.

`

Lance Hietpas
  • 351
  • 1
  • 5
  • 17
  • Have you read the file using some I/O API, i.e. http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path- ? – Arman Nov 13 '16 at 23:01
  • Not yet. I created the string from a site url that ended in .txt I am not hoping to seperate the multiple names such as name1.xml name2.xml in the string and put each name.xml into the ArrayList that I created. Then in the future use the items in the ArrayList to access the information in the seperate xml files. I'm just working on the for loop first, but am stuck on what I need to do to seperate and pull out the names. – Lance Hietpas Nov 13 '16 at 23:09

1 Answers1

1

You don't share what your delimiter is, but something like this will work:

final String DELIMITER = " "; // using space
String example = "one.xml two.xml three.xml";
List<String> items = Arrays.asList(example.split(DELIMITER));

for (String item : items) { // test output
    System.out.println(item);
}

You'd probably be best just adding it to the List when you read the file unless you need the String representing the file contents for some other purpose. For example using Scanner:

Scanner sc = new Scanner(new File("file.txt")); // default delimiter is whitespace
/**
 * or if using a custom delimiter:
 * final String DELIMITER = " "; // using space
 * Scanner sc = new Scanner("file.txt").useDelimiter(DELIMITER);
 */
List<String> items = new ArrayList<>();
while (sc.hasNext()) {
    items.add(sc.next());
}

for (String item : items) { // test output
    System.out.println(item);
}

file.txt

one.xml

two.xml

three.xml

d.j.brown
  • 1,822
  • 1
  • 12
  • 14