从JFileChooser创建ArrayList而不是硬编码选项

时间:2013-07-08 18:39:39

标签: java swing csv jfilechooser

我目前通过硬编码ArrayList访问我的.csv文件。我希望能够选择文件,而不是像目前那样进行硬编码。

我刚添加了JFileChooser。我无法让我的rowData逐行读取通过JOptionPane选择的文件。我该怎么做?

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV Files", "csv");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION)
    {
        System.out.println("You chose to open file: " + chooser.getSelectedFile().getName());
    }

我的原始代码从这里开始(没有注释行),它的工作原理。我只是不希望它硬编码。

    ArrayList<String> rowData = new ArrayList<String>();
    FileConnections excelConn = new FileConnections();
    //rowData = excelConn.read(chooser);
    rowData = excelConn.read(new File("11738 IPACC INFINITY Unconfirmed OIVS Responses.csv"));

1 个答案:

答案 0 :(得分:1)

试试这个(未经测试的顺便说一句!):

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV Files", "csv");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
    System.out.println("You chose to open file: " + chooser.getSelectedFile().getName());
    ArrayList<String> rowData = new ArrayList<String>();
    FileConnections excelConn = new FileConnections();
    rowData = excelConn.read(chooser.getSelectedFile());
}

相当于:

JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    System.out.println("You chose to open file: " + chooser.getSelectedFile().getName());
    ArrayList<String> rowData = new FileConnections().read(chooser.getSelectedFile());
}