public static ArrayList<String> get_arraylist_from_file(File f) throws FileNotFoundException {
Scanner scanner;
ArrayList<String> list = new ArrayList<String>();
scanner = new Scanner(f);
String s = scanner.nextLine();
while(scanner.hasNextLine()){
String[] tempList = s.split("&"); //This will give you this [title][ DVD]
String title = tempList[0];
String type = tempList[1].subString(1); //If you want the input at the place of DVD, with the space removed
list.add(title);
s = scanner.nextLine();
}
scanner.close();
return list;
}
java tokenize strings read from a text file
Question
I have this program that reads a text file from my computer. the text file is a list of titles. Im trying to figure out how to tokenize what is returned so that I get the full name instead of a piece. All the examples I am able to find involve regular arrays and Im using an arraylist. I need to be able to read each string back into my arraylist and cut it off where the & are.
The Text file looks like this:
Star Wars& DVD&
Lord of the Rings& DVD&
Resident Evil& DVD&
public static void main(String[] args) {
File f = new File("file.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;
}
La solution
Autres conseils
while (s.hasNextLine()) {
list.add(s.nextLine().replaceAll("&", ""));
}
removes the ampersands
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow