繁体   English   中英

Java使用文件选择器从CSV文件读取

[英]Java use a file chooser to read from a csv file

我有我的密码

import java.io .*;
import java.util.Arrays;

public class Inputtheta {
public static void main (String [] arg) throws Exception{
    BufferedReader CSVFile = new BufferedReader (new FileReader         ("/Users/Carolina/Documents/IST/AMC/init.csv"));
    String dataRow = CSVFile.readLine();


    while (dataRow != null && !dataRow.isEmpty()){
        String [] dataArray = dataRow.split (",");
        double[] doubleArray =new double[dataArray.length];
        int i=0;
        while (i< dataArray.length ) {
        doubleArray[i]= Double.parseDouble(dataArray[i]);
        i++; 
        }
        System.out.println(Arrays.toString(doubleArray));
        dataRow = CSVFile . readLine ();
        }
     CSVFile.close ();
      }

}

它从我直接询问的文件中读取数据,并将其数据保存到字符串中。 我的问题是,除了直接放入该文件外,我如何添加Filechooser? 我已经设法在GUI中打开该文件,但是我想知道如何在上面的代码中实际使用此文件。

 public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(Escolherficheiros.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);
        } else {
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());


    } 
}

[注意:尚未尝试编译或运行您的代码]

如果只想弹出JFC而没有其他任何元素,则可以将null传递给JFC.showOpenDialog()。 由于您将在没有其他任何swing / awt元素的情况下启动该控件,因此它不会处于actionPerformed方法中。

我只会用类似

private static File getFile(){
    JFileChooser fc = new JFileChooser();
    File file = null;
    int returnVal = fc.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = fc.getSelectedFile();  
    } 
    return file;
}

并从您的main方法调用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM