DefaultTableModel正在保存到文件但是如何加载文件以再次使用它?

时间:2012-12-13 07:49:15

标签: java swing file jtable defaulttablemodel

我正在尝试将JTable的内容保存到文件中,然后在需要时打开文件以显示原始JTable。我正在使用DefaultTableModel向JTable添加行和列,因此我决定将模型保存到文件中。这是我的方法:

public void outputfile(DefaultTableModel model) {
        String filename = "data.file";
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
            oos.writeObject(model);
            oos.close();
        }
        catch(IOException e) {
            System.out.println("There was a problem creating file: " + e);
            return;
        }
        System.out.println("JTable correctly saved to file " + filename);
    }

所以现在我的模型保存到data.file,我有一个打开文件的方法。或者......这就是它应该做的事情:

public void inputfile() {
        String filename = "data.file";
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
            model = (DefaultTableModel)ois.readObject();
        }
        catch(Exception e) {
            System.out.println("Problem reading back table from file: " + filename);
            return;
        }
    }

所以,在我的主要内容中我只写:

outputfile(model); //to save model to file.

inputfile();  //to extract model from file and then apply it to the table.
table = new JTable(model);

所以,谢谢你的阅读,但它不起作用。使用inputfile时没有任何反应。请帮忙吗?

public void writefile2(JTable table) {
        try{
        FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        TableModel model = table.getTableModel();
        for(int i = 0; i<model.getRowCount(); i++) {
            for(int j = 0; j<model.getColumnCount(); j++) {
                out.write((String)model.getValueAt(i, j));
            }
        }
        out.close();
        }catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        }
    }

1 个答案:

答案 0 :(得分:1)

此代码会将JTable转储到文件

TableModel model = table.getModel();

for( int i = 0; i < model.getRowCount(); i++ )
{
   for( int i = 0; i < model.getColumnCount(); j++ )
   {
   //Create your File Writer
   fileWriter.write( model.getValueAt( i, j );
   }
}

反方向可以拨打setValueAt()