简体   繁体   中英

Java use a file chooser to read from a csv file

I have my code

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 ();
      }

}

Which reads from a file that I directly ask, and saves its data into strings. My question is, instead of putting directly that file, how can I include a Filechooser? I already managed to open the file in my GUI, but I wanted to know how to actually use this file in the code above.

 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());


    } 
}

[note: have not attempted to compile or run your code]

If you want to simply have the JFC pop up without any other elements, you can pass null to the JFC.showOpenDialog(). Since you would be launching that without any other swing/awt elements, it would not be in an actionPerformed method.

I would just use something like

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;
}

and call that from your main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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