How to use JFileChooser to show in a table a csv file with any name to read and edit this same file

197 Views Asked by At

I made a program to help me with some spreadsheets and it works perfectly, but I would like to be able to select any csv file using JFileChooser and to be able to edit the file that was selected. The way I did it, I always force the file to have a specific name and i dont want like this. How can I do this? I've done some research, but to no success. Thanks

enter code here
//my list, write, remove and update file    
File fileName = new File("file.csv"); 

@Override
public ArrayList<Data> list() throws Exception {        
    try{            
        ArrayList<Data> listData = new ArrayList<>();
        FileReader fr = new FileReader(fileName);
        try ( 
                BufferedReader br = new BufferedReader(fr)) {
                String line;
                while((line=br.readLine())!=null){
                Data objData = new Data(line);
                listData.add(objData);
            }br.close();
        }
        return listData;
    }catch(IOException erro){
    throw erro;
    }
}

@Override
public void add(Data objData) throws Exception {
    try{
       FileWriter fw = new FileWriter(fileName,true);
        try ( 
            BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(objData.toString()+"\n");
        }
    }catch(IOException erro){
        throw erro;
    }
}

@Override
public void remove(int code) throws Exception{
    ArrayList<Data> list;
    list = list();
    if(list.isEmpty()) return;
    FileWriter fw = new FileWriter(fileName);
    try ( 
            BufferedWriter bw = new BufferedWriter(fw)) {
        for(Data p : list){
            if(p.getCode() != code){
                bw.write(p.toString()+"\n");
            }
        }
    }
}    

@Override
public void update(Data objData) throws Exception {
    try{
        ArrayList<Data> list;
        list = list();
        if(list.isEmpty()) return;
        FileWriter fw = new FileWriter(fileName);
        try ( 
                BufferedWriter bw = new BufferedWriter(fw)) {
            for(Data p : list){
                if(p.getCode() != objData.getCode()){
                    bw.write(p.toString()+"\n");
                }else{
                    bw.write(objData.toString()+"\n");
                }
            }
        }
   }catch(Exception erro){
        throw erro;
    }
}

enter code here
//my UI table list    
private void showData(){
    try{
        ArrayList<Data> list;
        DataDAO Data = new DataDAO();            
        list = Data.list();
        if (list.isEmpty()) return;
        DefaultTableModel model = (DefaultTableModel) jTable_Table1.getModel();
        model.setNumRows(0);
        for(int pos=0; pos < list.size(); pos++){
            String[] line = new String[6];
            Data aux = list.get(pos);
            line[0] = aux.getCode()+"";
            line[1] = aux.getName();
            line[2] = aux.getPrice()+"";
            line[3] = aux.getCargoN()+"";
            line[4] = aux.getTotal_Weight()+"";
            line[5] = aux.getTotal_Vol()+"";
            model.addRow(line);
        }
    }catch (Exception erro){
        JOptionPane.showMessageDialog(rootPane, erro.getMessage());
    }
}

// MY button jfilechooser    
private void open_file() throws Exception{
    try{  
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "Only csv", "csv");
        chooser.setFileFilter(filter);
        chooser.setCurrentDirectory(new File("./"));
        int result = chooser.showOpenDialog(getParent());
        if (result == JFileChooser.APPROVE_OPTION) 
        {                
            File selectedFile = chooser.getSelectedFile();
            String file = selectedFile.getAbsolutePath();
            System.out.println(file);
            showData();            
        }            
    }catch(HeadlessException erro){
        JOptionPane.showMessageDialog(rootPane, erro);
    } 
}
1

There are 1 best solutions below

0
MadProgrammer On

In simple terms, something like ...

private JFileChooser fileChooser;

public File getFile(Component parent) {
    if (fileChooser == null) {
        fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Make a choice");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("csv", "CSV");
        fileChooser.addChoosableFileFilter(filter);
    }
    int option = fileChooser.showOpenDialog(parent);
    if (option == JFileChooser.APPROVE_OPTION) {
        return fileChooser.getSelectedFile();
    }
    return null;
}

Which is largely covered by How to Use File Choosers

You could add this to your existing class or make a utility class depending on your needs.

You will need to change your workflow to have some kind of "open file" step, which would call this and return the "selected file", making sure you take into account the possibility of a null value. You'd then assign this value to File fileName;, this would allow your other workflows to continue operating.

The "hows" of how you would do this are implementation dependent and you're going to have to play around with yours to figure out the best place(s) to make use of it