Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

java - When export jTable data to Text file & import back data not in proper order

Text FileAfter Importing DataJTable with existing data I attempt to Export JTable data to Text File and Import data back to same JTable. But data not in proper order in Text File & JTable as shown images. Some cells in table fills with two or more words. Help me to solve the issue is highly appreciate? Thanks in advance.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class SaveTest1 extends javax.swing.JFrame{
    
    public SaveTest1() {
        initComponents();
        setLocationRelativeTo(null);
    }
    
    @SuppressWarnings("unchecked")                     
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jFileChooser1 = new javax.swing.JFileChooser();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"1", "Engineering Brick", "Nos", "18.00", "550", "9900.00"},
                {"2", "River Sand", "Cube", "15000.00", "0.1", "1500.00"},
                {"3", "Cement", "cwt", "1100.00", "3", "3300.00"},
                {null, null, null, null, "Cost of Material", "14700.00"}
            },
            new String [] {
                "ID", "Name", "Unit", "Price", "Qty", "Amount"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.weighty = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jButton1.setText("Export");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jButton1, gridBagConstraints);

        jButton2.setText("Import");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jButton2, gridBagConstraints);

        pack();
    }                       

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Save as");
       
        int userSelection = fileChooser.showSaveDialog(this);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();

            try {
                FileWriter fw = new FileWriter(fileToSave);
                BufferedWriter bw = new BufferedWriter(fw);

                for (int i = 0; i < jTable1.getColumnCount(); i++) {
                    
                    bw.write(jTable1.getColumnName(i));
                    bw.write("");

                }
                for (int i = 0; i < jTable1.getRowCount(); i++) {
                    bw.newLine();
                    for (int j = 0; j < jTable1.getColumnCount(); j++) {
                        bw.write((String) jTable1.getValueAt(i,j));
                        String val = (String) jTable1.getValueAt(i, j);
                        if (val == null) {
                        val = "";
                        }
                        bw.write("");
                    }
                }
                JOptionPane.showMessageDialog(this, "File Saved", "Information", JOptionPane.INFORMATION_MESSAGE);
                
                bw.close();
                fw.close();
                
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Error", "Error Message", JOptionPane.ERROR_MESSAGE);
            }
        }
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Open");
       
        int userSelection = fileChooser.showOpenDialog(this);
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToOpen = fileChooser.getSelectedFile();
            
            try {
            FileReader fr = new FileReader(fileToOpen);
            BufferedReader br = new BufferedReader(fr);

            DefaultTableModel model1 = (DefaultTableModel) jTable1.getModel();
            Object[] lines = br.lines().toArray();

            for (int i = 1; i < lines.length; i++) {

                String[] row = lines[i].toString().split(" ");
                model1.addRow(row);
            }

        } catch (Exception ex) {
            Logger.getLogger(SaveTest1.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       DefaultTableModel model1 = (DefaultTableModel) jTable1.getModel();
        model1.setRowCount(0);
    }       
    
    
    public static void main(String args[]) {
       
        
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SaveText.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SaveText.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SaveText.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SaveText.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SaveText().setVisible(true);
            }
        });
    }

                    
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
                   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When writing to file you separate cells by a tab char, bw.write("");, but when reading the data back in, you use space, String[] row = lines[i].toString().split(" "); to identify the border of each cell. Don't do this. Use the same char or String to separate the cells both when you write and when you read back in.

Consider

String[] row = lines[i].split("", -1);

instead

Also, better to convert the Stream to a String-specific array and not an Object array:

String[] lines = br.lines().toArray(String[]::new);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...