我目前通过硬编码的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"));
最佳答案
试试这个(顺便说一句!):
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());
}
关于java - 从JFileChooser创建ArrayList而不是硬编码选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17533699/