实现备份与还原,需用到的方法

来源:互联网 发布:人工智能编程 编辑:程序博客网 时间:2024/06/05 10:01
//写入文件
public void wirteFile(File f){
try {
bytes= null; 
ByteArrayOutputStream bos = new ByteArrayOutputStream();     
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);       
oos.flush();        
bytes = bos.toByteArray();  
FileOutputStream outputStream=new FileOutputStream(f);
outputStream.write(bytes);
oos.close();        
bos.close();  
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}        
}
//读文件
public void readFile(File f){
FileInputStream inputStream=new FileInputStream(f);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*5];
int length = -1;
while((length = inputStream.read(buffer)) != -1 ){
outStream.write(buffer, 0,length);
bytes=outStream.toByteArray();   
}
outStream.close();
inputStream.close();
List newList=(List<Users>) toObject(bytes);
}
//bytes转换成对象
public Object toObject(byte[] bytes){     
Object obj = null; 
        try {       
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);       
            ObjectInputStream ois = new ObjectInputStream (bis);       
            obj = ois.readObject();     
            ois.close();  
            bis.close();  
        } catch (IOException ex) {       
            ex.printStackTrace();  
        } catch (ClassNotFoundException ex) {       
            ex.printStackTrace();  
        }     
        return obj;   
    }  
0 0
原创粉丝点击