0

我正在尝试将 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);

所以,感谢您阅读,但它不起作用。当我使用输入文件时没有任何反应。请帮忙?

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());
        }
    }
4

1 回答 1

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()

于 2012-12-13T08:04:20.797 回答