backupimpl.java

来自「springGather 在JAVA环境开发的电信运营支持系统」· Java 代码 · 共 114 行

JAVA
114
字号
package org.com.gather;

import java.util.*;
import java.io.*;

public class BackUpImpl implements BackUp{
	private Properties pro = null;
	private Log log = null;

	public BackUpImpl(Properties pro){
		this.pro = pro;
	}

	public void store(Collection col){
		File file = new File(pro.getProperty("backUpFile"));
		try{
			file.createNewFile();
		}catch(IOException e){
			e.printStackTrace();
		}	

		ObjectOutputStream oos = null;
		try{
			Collection c = this.load();
			if(!c.isEmpty()){
				log.writeDebug("之前有备份数据!");
				c.addAll(col);
				col = c;
			}
			oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(col);
			log.writeDebug("成功将数据写入到备份文件!");
		}catch(IOException e){
			e.printStackTrace();
			log.writeDebug("写入备份文件失败!");
		}
	}

	public void storeForEmpty(Collection col){
		File file = new File(pro.getProperty("backUpFile"));
		try{
			file.createNewFile();
		}catch(IOException e){
			e.printStackTrace();
		}	

		ObjectOutputStream oos = null;

		if(!col.isEmpty()){
			try{
				oos = new ObjectOutputStream(new FileOutputStream(file));
				oos.writeObject(col);
				log.writeDebug("再次采集到的数据为空,把备份文件再次写回到文件;");
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

	public Collection load(){
		File file = new File(pro.getProperty("backUpFile"));
		try{
			file.createNewFile();
		}catch(IOException e){
			e.printStackTrace();
		}
		ObjectInputStream ois = null;
		if (file.length() < 1) {
			//如果长度为0表示该文件为新建的.这个时候
			//用readObject()就会报EOFException
			log.writeDebug("备份文件为空!");
			return new ArrayList();
		}else{
			try{
				ois = new ObjectInputStream(new FileInputStream(file));

				Object o = ois.readObject();
				if(o != null){
					Collection col = (Collection)o;
					return col;
				}else{
					return new ArrayList();
				}
			}catch(FileNotFoundException e){
				e.printStackTrace();
				return null;
			}catch(IOException e){
				e.printStackTrace();
				return null;
			}catch(ClassNotFoundException e){
				e.printStackTrace();
				return null;
			}
		}
	}

	public void clear(){
		File file = new File(pro.getProperty("backUpFile"));
		OutputStream os = null;
		ObjectOutputStream oos = null;
		try{
			os = new FileOutputStream(file);
			oos = new ObjectOutputStream(os);
			oos.writeObject(new ArrayList());
		}catch(IOException e){
			e.printStackTrace();
			log.writeDebug("清空备份文件失败;");
		}
	}

	public void setLog(Log log){
		this.log = log;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?