I’m working with java Scanner trying to extract product information from a text file called Inventory.txt.
This file contains data on products in this format:
“Danelectro|Bass|D56BASS-AQUA|336177|395.00Orange|Amplifier|BT1000-H|319578|899.00Planet Waves|Superpicks|1ORD2-5|301075|4.50Korg|X50 Music Synthesizer|X50|241473|735.00Alpine|Alto Sax|AAS143|198490|795.00”
I am trying to parse the strings and add them into an arraylist such that each element in the arraylist would look something like this:
"Danelectro|Bass|D56BASS-AQUA|336177|395.00"
"Orange|Amplifier|BT1000-H|319578|899.00"
"KorPlanet Waves|Superpicks|1ORD2-5|301075|4.50"
"g|X50 Music Synthesizer|X50|241473|735.00"
"Alpine|Alto Sax|AAS143|198490|555.00”
Following is my code:
public class ItemDao {
public ItemDao() {
scanFile();
}
public void scanFile() {
Scanner scanner;
ArrayList <String> content = new ArrayList <String>();
try {
Pattern p1 = Pattern.compile("\\.[0-9]{2}$");
scanner = new Scanner(new File("Inventory.txt"));
while (scanner.hasNext(p1)) {
content.add(scanner.next(p1));
}
for (String item : content) {
System.out.println("Items:" + item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
When I tested this code I found that the arraylist is empty. Any help would be much appreciated.
java -jar A00123456Lab5.jar
Create an ItemDAO class in a dao package
This class will contain an static inner class which implements Comparator
(DAO = Data Access Object)
I see you’re using a pattern, those can come in handy–but I’d just take each line and substring it.
Just a thought–might be easier to debug with this way.