Java Import Text File Data To JTable

How To Populate JTable From Txt File Text Using Java NetBeans

Import Txt File Data To JTable Using Java



In this Java Tutorial we will see How To Import Text From Text File And Set It Into JTable Rows Using BufferedReader +  DefaultTableModel On JButton Click In Java programming language and NetBeans IDE .




Project Source Code:

private void jButtonImportActionPerformed(java.awt.event.ActionEvent evt) {                                              
        
        String filePath = "C:\\Users\\Desktop\\table.txt";
        File file = new File(filePath);
        
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            // get the first line
            // get the columns name from the first line
            // set columns name to the jtable model
            String firstLine = br.readLine().trim();
            String[] columnsName = firstLine.split(",");
            DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
            model.setColumnIdentifiers(columnsName);
            
            // get lines from txt file
            Object[] tableLines = br.lines().toArray();
            
            // extratct data from lines
            // set data to jtable model
            for(int i = 0; i < tableLines.length; i++)
            {
                String line = tableLines[i].toString().trim();
                String[] dataRow = line.split("/");
                model.addRow(dataRow);
            }
            
            
        } catch (Exception ex) {
            Logger.getLogger(TextFileDataToJTable.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 


OutPut:

Populate JTable Using Text File Text In Java



Share this

Related Posts

Previous
Next Post »

5 comments

comments
14 juillet 2018 à 08:00 delete

Object[] tableLines = br.lines().toArray();
lines()
does not exist, why?

Reply
avatar
21 avril 2019 à 00:35 delete

me the same thing:
lines()
does not exist, why?

Reply
avatar
7 juillet 2019 à 23:16 delete

how to resolve mtehod lines() which not exist ?

Reply
avatar
Anonyme
6 août 2022 à 17:39 delete

It's perfect, thank you!

Reply
avatar