Java实现DefaultTableModel数据的文件写入读取

问题:

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

参考
https://stackoverflow.com/q/21874539

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值