tags:

views:

377

answers:

2

I have the following file saved as a .txt:

I Did It Your Way, 11.95
The History of Scotland, 14.50
Learn Calculus in One Day, 29.95
Feel the Stress, 18.50
Great Poems, 12.95
Europe on a Shoestring, 10.95
The Life of Mozart, 14.50

I need to display the title of the books and the prices on different JLists in Java. How do I do that?

Also if I have an array with two values (once I separate the title from the price) how do I copy the title and price into their respective arrays?

+4  A: 

Seems simple enough that you don't need anything fancy.

BufferedReader r = new BufferedReader(new FileReader("file.txt"));
List<String> titles = new ArrayList<String>();
List<Double> prices = new ArrayList<Double>();

while ((String line = r.readLine()) != null) {
  String[] tokens = line.split(",");
  titles.add(tokens[0].trim());
  prices.add(Double.parseDouble(tokens[1].trim()));
}

r.close();
Apocalisp
A: 

If the values are separated by comma, you can use http://opencsv.sourceforge.net/ . Here is the sample code,

            CSVReader reader = new CSVReader(new FileReader("test.txt"));
 List myEntries = reader.readAll();

 int noOfEntries=myEntries.size();

 String[] titles=new String[noOfEntries]; 
 String[] price=new String[noOfEntries]; 

 String[] entry=null;
 int i=0;
 for(Object entryObject:myEntries){
  entry=(String[]) entryObject;
  titles[i]=entry[0];
  price[i]=entry[1];
  i++;
            }
Adi