Lance Hietpas Lance Hietpas - 19 days ago 5
Android Question

Java Iterate through a string and pull out sections to add to an ArrayList

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.

`

Answer

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

Comments