将 jTable 数据导出到文本文件并按顺序导入回数据时

问题描述

Text FileAfter Importing DataJTable with existing data 我尝试将 JTable 数据导出到文本文件并将数据导入回同一个 JTable。但是文本文件和 JTable 中的数据顺序不正确,如图所示。表格中的某些单元格填充了两个或多个单词。帮我解决问题是高度赞赏?提前致谢。

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

            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);
        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);
        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);
        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("\t");

                }
                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("\t");
                    }
                }
                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,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,ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SaveText.class.getName()).log(java.util.logging.Level.SEVERE,ex);
        } catch (illegalaccessexception ex) {
            java.util.logging.Logger.getLogger(SaveText.class.getName()).log(java.util.logging.Level.SEVERE,ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SaveText.class.getName()).log(java.util.logging.Level.SEVERE,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;
                   
}

解决方法

写入文件时,您用制表符 bw.write("\t"); 分隔单元格,但读回数据时,您使用空格 String[] row = lines[i].toString().split(" "); 来标识每个单元格的边框。不要这样做。在写入和读回时使用相同的字符或字符串来分隔单元格。

考虑

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

代替

此外,最好将 Stream 转换为 String-specific 数组而不是 Object 数组:

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