java objectinpustream读取defaulttablemodel

ruyhziif  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(343)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

13天前关门了。
改进这个问题
有一个类正在保存另一个类的defaulttablemodel。

file_path = new File( "c://Database//Directory//" );

file_table_stock_save = new File( file_path , "stockfile.file" );

file_path.mkdirs();

try
{

 file_path..createNewFile();

 fileoutputstream = new FileOutputStream( file_table_stock_save );

 objectoutputstream = new ObjectOutputStream( fileoutputstream );

 objectoutputstream.writeObject( stock.defaulttablemodel );

 objectoutputstream.close();

 fileoutputstream.close();

}

  catch( Exception exception )
  {.....}

下面是如何读取defaulttablemodel

file = new File( "C://Database//Directory//" , "stockfile.file" );

object = new Object();

if( file.exists() )
{

 try
 {

  fileinputstream = new FileInputStream( file );
  objectinputstream = new ObjectInputStream( fileinputstream );

  object = objectinputstream.readObject();

  objectinputstream.close();
  fileinputstream.close();

 }

 catch( Exception exception )
 {}

 try
 {

  if( !( object == null ) )
  defaulttablemodel = ( DefaultTableModel ) object;

 }

 catch( Exception exception )
 {......}

问题是文件总是存在,但有时无法读取。如何解决这个问题?类应该实现可序列化吗?jtable中的空单元格在读取时会导致错误吗?

jhdbpxl9

jhdbpxl91#

首先,我绝不会序列化defaulttablemodel,否则您将序列化不想序列化的内容,包括侦听器等。最好保持简单,序列化数据,并且只序列化数据。我将序列化包含感兴趣的数据的数据向量。使用它可以用检索到的数据重建新的表模型。
幸运的是defaulttablemodel有一个方法, .getDataVector() 从模型a中检索 Vector<Vector> 它保存模型中的所有数据。如果必须使用序列化,我将使用它来保存和检索数据。
在下面的代码中,我有一个简单的类,它扩展了defaulttablemodel,并允许用一个数据向量重新创建模型,使用一个常量向量来保存表标题:

class MyModel extends DefaultTableModel {
    public static final String[] HEADERS = { "One", "Two", "Three" };
    public static final Vector<String> V_HEADERS = new Vector<>(Arrays.asList(HEADERS));

    public MyModel(Vector<Vector<Object>> data) {
        super(data, V_HEADERS);
    }

    public MyModel() {
        super(HEADERS, 0);
    }

}

然后,我可以通过以下代码序列化和取消序列化模型持有的数据:

// assuming that the model is held in a variable called "myModel"
Vector tableData = myModel.getDataVector();
        // file name is held by DATA_FILE String constant
try (FileOutputStream fos = new FileOutputStream(DATA_FILE); 
        ObjectOutputStream oos = new ObjectOutputStream(fos);) {
    oos.writeObject(tableData);  // writes my data 

} catch (IOException ioe) {
    ioe.printStackTrace(); // always catch and handle exceptions
}

我可以将数据读回模型,然后通过以下方式读入jtable:

// again DATA_FILE is our file's name
try (FileInputStream fis = new FileInputStream(DATA_FILE); 
        ObjectInputStream ois = new ObjectInputStream(fis)) {
    // read the data vector in with the ObjectInputStream
    Vector<Vector<Object>> tableData = (Vector<Vector<Object>>) ois.readObject();

    // create a new table model with the data
    myModel = new MyModel(tableData);

    // set the JTable with the new model
    table.setModel(myModel);
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}

一个有效的例子:

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Gui01 extends JPanel {
    public static final String DATA_FILE = "tableData.dat";
    private MyModel myModel = new MyModel();
    private JTable table = new JTable(myModel);

    public Gui01() {
        int maxRow = 5;
        for (int row = 0; row < maxRow; row++) {
            Vector<Object> rowData = new Vector<>();
            for (int col = 0; col < table.getColumnCount(); col++) {
                Integer cell = row * table.getColumnCount() + col;
                rowData.add(cell);
            }
            myModel.addRow(rowData);
        }

        saveTable();

        JButton saveTableBtn = new JButton("Save Table");
        saveTableBtn.setMnemonic(KeyEvent.VK_S);
        saveTableBtn.addActionListener(e -> saveTable());

        JButton clearTableBtn = new JButton("Clear Table");
        clearTableBtn.setMnemonic(KeyEvent.VK_C);
        clearTableBtn.addActionListener(e -> clearTable());

        JButton retrieveTableBtn = new JButton("Retrieve Table");
        retrieveTableBtn.setMnemonic(KeyEvent.VK_R);
        retrieveTableBtn.addActionListener(e -> retrieveTable());

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(saveTableBtn);
        buttonPanel.add(clearTableBtn);
        buttonPanel.add(retrieveTableBtn);

        setLayout(new BorderLayout());
        add(new JScrollPane(table));
        add(buttonPanel, BorderLayout.PAGE_END);

    }

    @SuppressWarnings("rawtypes")
    private void saveTable() {
        Vector tableData = myModel.getDataVector();
        try (FileOutputStream fos = new FileOutputStream(DATA_FILE);
                ObjectOutputStream oos = new ObjectOutputStream(fos);) {
            oos.writeObject(tableData);

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    private void clearTable() {
        myModel.setRowCount(0);
    }

    @SuppressWarnings("unchecked")
    private void retrieveTable() {
        try (FileInputStream fis = new FileInputStream(DATA_FILE); 
                ObjectInputStream ois = new ObjectInputStream(fis)) {
            Vector<Vector<Object>> tableData = (Vector<Vector<Object>>) ois.readObject();
            myModel = new MyModel(tableData);
            table.setModel(myModel);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        Gui01 mainPanel = new Gui01();
        JFrame frame = new JFrame("Gui01");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}
class MyModel extends DefaultTableModel {
    public static final String[] HEADERS = { "One", "Two", "Three" };
    public static final Vector<String> V_HEADERS = new Vector<>(Arrays.asList(HEADERS));

    public MyModel(Vector<Vector<Object>> data) {
        super(data, V_HEADERS);
    }

    public MyModel() {
        super(HEADERS, 0);
    }
}

相关问题