简体   繁体   中英

DefaultTableModel is saving to a file but how can I load the file to use it again?

I'm trying to save the contents of a JTable to a file and then open the file when needed to bring up the original JTable. I am using the DefaultTableModel to add rows and columns to the JTable so I decided to save my model to a file. Here is my method:

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

So now that my model is saved to data.file, I have a method that opens the file. Or...that's what it's supposed to do:

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

So, in my main I simply write:

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

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

So, thank you for reading but it's not working. Nothing happens when I use inputfile. help please?

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

This code would dump JTable to a file

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

In reverse direction you can call setValueAt()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM