Java Import And Export Text File To JTable

How To Get And Set Jtable Data To Txt File Using Java NetBeans

Export And Import Text File To JTable Using Java



In this Java Tutorial we will see How To Import Text From Text File And Set It Into JTable Rows & Export JTable Rows Data To A Txt File Using FileWriter  +  BufferedWriter  + FileReader In Java NetBeans .




Project Source Code:


// button to export data to text file
private void jButtonExportActionPerformed(java.awt.event.ActionEvent evt) {                                              
        
        String filePath = "C:\\Users\\omar\\Desktop\\myfolder\\txtfile.txt";
        File file = new File(filePath);
        try {
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            
            for(int i = 0; i < jTableExport.getRowCount(); i++){//rows
                for(int j = 0; j < jTableExport.getColumnCount(); j++){//columns
                    bw.write(jTableExport.getValueAt(i, j).toString()+" ");
                }
                bw.newLine();
            }
            
            bw.close();
            fw.close();
            
        } catch (IOException ex) {
            Logger.getLogger(JTable_import_and_export_to_text_file.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }                                             


// button to import data from text file
    private void jButtonImportActionPerformed(java.awt.event.ActionEvent evt) {                                              
      
        String filePath = "C:\\Users\\omar\\Desktop\\myfolder\\txtfile.txt";
        File file = new File(filePath);
        
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            
            DefaultTableModel model = (DefaultTableModel)jTableImport.getModel();
            Object[] lines = br.lines().toArray();
            
            for(int i = 0; i < lines.length; i++){
                String[] row = lines[i].toString().split(" ");
                model.addRow(row);
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JTable_import_and_export_to_text_file.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    } 


OutPut:

Set And Get Jtable Data To Txt File In Java



Share this

Related Posts

Previous
Next Post »

4 comments

comments
21 avril 2019 à 00:44 delete

lone:
Object[] lines = br.lines().toArray();

lines()//Do not exists

Reply
avatar
22 avril 2019 à 22:43 delete

Need help as i get an error with Export

Reply
avatar
28 mars 2020 à 14:19 delete

Hello sir, I get error with export file. I will appreciate if you reply me.Thank you

Reply
avatar
Niq
7 janvier 2023 à 22:47 delete

Hi, why the error says that cannot find symbol of jTableImport?

Reply
avatar