问题:
1.JAVA的DefaultTableModel的数据如何保存为文件?
2.保存的文件如何打开读取到表格模型中?
解决要点:
1.使用对象字节输入输出流.
2.使用getDataVector()方法实现表格模型数据写入.
3.使用Vector类及setDataVector()方法实现表格模型数据读取.
TableModelFile类代码:
package pack;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.File;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class TableModelFile {
public static void writeTo(DefaultTableModel model, File file) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(model.getDataVector());
}
catch (Exception e) { e.printStackTrace(); }
finally {
if(oos != null)
try { oos.close(); }
catch (IOException e) { }
}
}
public static void readFrom(DefaultTableModel model, File file) {
int col = model.getColumnCount();
String[] colnames = new String[col];
Vector<String> title = new Vector<String>();
for(int i=0; i<col; i++) {
colnames[i] = model.getColumnName(i);
title.add(colnames[i]);
}
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
Vector data = (Vector)ois.readObject();
model.setDataVector(data, title);
}
catch (Exception e) { e.printStackTrace(); }
finally {
if(ois != null)
try { ois.close(); }
catch (IOException e) { }
}
}
}
使用范例:
public void actionPerformed(ActionEvent event) {
if(event.getSource() instanceof JButton)
{
switch(event.getActionCommand())
{
case "打开":
if(openfile.showOpenDialog(this)==0)
{
this.file = openfile.getSelectedFile();
TableModelFile.readFrom(tablemodel, this.file);
}
break;
case "保存":
if(savefile.showSaveDialog(this)==0)
{
this.file = savefile.getSelectedFile();
TableModelFile.writeTo(tablemodel, this.file);
}
break;
}
}
}