我将以下文件另存为.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
我需要在Java中显示不同JList
的书籍标题和价格。我该怎么做?
此外,如果我有一个包含两个值的数组(一旦我将标题与价格分开),我如何将标题和价格复制到各自的数组中?
答案 0 :(得分:4)
看起来很简单,你不需要任何花哨的东西。
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();
答案 1 :(得分:0)
如果值以逗号分隔,则可以使用http://opencsv.sourceforge.net/。以下是示例代码
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++;
}