将csv文件导入到Java swing表中

我有一个nyse中所有股票报价的csv文件.第一列是符号,第二列是公司名称.

我有一个使用java swing库在netbeans中制成的搜索框和表.

现在,当我在框中输入名称时,它会返回正确的行数.因此,例如,如果我搜索GOOG,它将仅返回2行(GOOG符号1行,公司全名中1行).但是,这些行中的数据不是正确的数据,它只是一遍又一遍地打印csv文件的第一行.这是单击搜索按钮时执行的代码:

package my.Stock;


import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.*;

public class searchy {

    public static void doSearch(String s){


                                  javax.swing.JTable resTable = StockUI.stockUI.getResultTable();
                                  javax.swing.table.DefaultTableModel dtm =
                                          (javax.swing.table.DefaultTableModel) resTable.getModel();

                                  while (dtm.getRowCount()> 0 ) dtm.removeRow(0);





            String sym = s.trim().toUpperCase();

try {

//csv file containing data
String strFile = "companylist.csv";

//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader(strFile));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;

//create arraylist
ArrayList<String> arrayList = new ArrayList<String>();

//read comma separated file line by line
while( (strLine = br.readLine()) != null){

lineNumber++;

//break comma separated line using ","
st = new StringTokenizer(strLine, ",");

while(st.hasMoreTokens()){

//display csv values
tokenNumber++;

arrayList.add(st.nextToken());
//System.out.println("Line # " + lineNumber + ": "+ st.nextToken() + " " + st.nextToken());
} //end small while

//reset token number
tokenNumber = 0;

} //end big while loop

//send csv to an array
Object[] elements = arrayList.toArray();
/*
for(int i=0; i < elements.length ; i++)    {
       System.out.println(elements[i]);

} */
Scanner input = new Scanner(System.in);
System.out.print("Enter Ticker symbol");
//String sym = input.next().toUpperCase(); //convert to uppercase to match csv
int j=0;
for(int i=0; i < elements.length ; i++)    {
  if (((String) elements[i]).contains(sym)){
      //System.out.println(elements[i]);

      dtm.addRow(elements);
      j++;
      if (j==25) break; //only show this many results
  }


}

}
catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
    }
}

我知道为什么会这样,但是我不确定如何告诉它打印正确的行,因为我不能使用dtm.addRow(elements [i]);.

任何帮助是极大的赞赏.

解决方法:

尝试CSVManager.

上一篇:Java-Netbeans:更改主类以生成JAR,同时排除原始主类


下一篇:如何使用Netbeans调试JavaScript代码?