0

我目前通过硬编码的 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"));
4

1 回答 1

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());
}
于 2013-07-08T18:49:38.177 回答