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