用IO流ObjectOutputStream导入导出一个Java对象

导出对象

1.首先导出一定是在表单form里实现的,配置好.do

<FORM id="form1" name=form1 method="post" action="<%=basePath %>/busi/busiTmptList.do?tokenid=<%=tokenID%>">

然后是具体导出的代码:

var formAction = $("#form1").attr("action");
$("#form1").attr("action",basePath+"busi/busiTmptExport.do?tokenid="+tokenID+"&busiTmptId="+busiTmptId);
$("#form1")[0].submit();

$("#form1").attr("action",formAction);

 

这里要注意一下,更好了action路径之后一定要在重新设置一遍,否则会之后点击别的需要提交表单的链接都会走导出!

 

2.下一步就是定义一个导出的对象,new ExportDto(),再去查你需要的各种数据class对象

将各种list放到导出对象里面.

3.执行导出成.ser文件

 

            ​
    //导出
	private void export(HttpServletRequest request,HttpServletResponse response,BusiTmptExportDto busiTmptExportDto,String busiTmptName){
		//获取根路径
		String path=request.getSession().getServletContext().getRealPath("/")+"\\abc.ser";
		try {
            FileOutputStream outStream = new FileOutputStream(path); 
			ObjectOutputStream os=new ObjectOutputStream(outStream);
			os.writeObject(busiTmptExportDto);
			os.flush();
			os.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		try {
            //再用流读取刷给浏览器,用户就可以自己用浏览器保存到自己想保存的位置了
			File file=new File(path);//第二步,读取文件,并下载
			String fileName=busiTmptName+".ser";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileName.getBytes("GBK"), "ISO-8859-1"));
			System.setProperty("sun.jnu.encoding","utf-8");
			InputStream is = new FileInputStream(file);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = is.read(b)) > 0) {
				os.write(b, 0, length);
			}
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//删除默认地址的文件
			File file=new File(path);
			//检查文件是否存在,如果不存在直接返回,不进行下面的操作
			if(!file.exists()){
				return;
			}
			//如果是文件删除,就删除文件,然后返回,不进行下面的操作
			if(file.isFile()){
				file.delete();
				return;
			}
		}
	}

导出对象里包含word文件:

我当时导出的是我们模块的所有的数据,也就是所有的对象,里面包括各种文件,这里需要导出附件存在标的里的数据,同时也需要导出真实的附件,附件数据信息就保存成一个list对象即可,文件就以二进制数组集合的形式保存到导出对象,因为我导入的时候调的是保存附件的借口,所以,就需要特定的格式的对象,

//附件
private List<AttachmentDto> attachmentDtos=new ArrayList<AttachmentDto>();
//文件
private Map<String,Map<File,byte[]>> fileMap=new HashMap<String,Map<File,byte[]>>();

 

导入对象文件

 

var formAction = $("#form1").attr("action");
		$("#form1").attr("action",basePath+"busi/busiTmptExport.do?tokenid="+tokenID+"&busiTmptId="+busiTmptId);
		$("#form1")[0].submit();
		$("#form1").attr("action",formAction);

 

List<AttachmentDto> attachmentDtos=new ArrayList<AttachmentDto>();
List<AttachmentDto> attachmentDtoList = attachmentApi.selectAttachmentBusiIds(wordTmptIds.toArray(new String[]{}));
//文件
Map<String,Map<File,byte[]>> fileMap=new HashMap<String,Map<File,byte[]>>();
for (AttachmentDto attachmentDto : attachmentDtoList) {
	if(attachmentDto!=null){
		Map<File,byte[]> byteMap=new HashMap<File, byte[]>();
		String path = attachmentDto.getFilePath();
		String attachmentId = attachmentDto.getAttachmentId();
		//文件解压缩
		File file = new File(attachmentDto.getFilePath());//AttachmentUtil.getHandledFile(attachmentDto);
		if(file.exists() && file.isFile()){
		    attachmentDtos.add(attachmentDto);
		    byte[] bytes = getBytes(path);
		    byteMap.put(file, bytes);
			fileMap.put(attachmentId, byteMap);
		}
	}
}
busiTmptExportDto.setAttachmentDtos(attachmentDtos);
busiTmptExportDto.setFileMap(fileMap);
			

 

导入对象就很简单了,只要将对象依次取出插入到表里就可以了.

 

	Map<String,Object> result = new HashMap<String, Object>();
    	String busiTmptTypeDictCode = request.getParameter("busiTmptTypeDictCode");
    	AttachmentDto attachmentDto = null;
    	InputStream in = null;
    	BusiTmptExportDto busiTmptExportDto=null;
		try {
			ObjectInputStream ois = null;
			attachmentDto = attachmentService.getById(request.getParameter("attachmentId"));
			if(attachmentDto!=null){
				String path = attachmentDto.getFilePath();
				//文件解压缩
				File busiTmptFile = AttachmentUtil.getHandledFile(attachmentDto);
				
				if(busiTmptFile==null){
					busiTmptFile = new File(path);
				}
				if(!(busiTmptFile.exists() && busiTmptFile.isFile())){
					result.put("flag", false);
					result.put("msg", "导入失败!");
					return result;
				}
				
				try {
		            in = new FileInputStream(busiTmptFile);
		            ois = new ObjectInputStream(in);
	                反序列化读取得到对象
	            	busiTmptExportDto = (BusiTmptExportDto) ois.readObject(); 
		            ois.close();
		        } catch (IOException e) {
		            e.printStackTrace();
		        } finally {
		            if (in != null) {
		                try {
		                    in.close();
		                } catch (IOException e1) {
		                }
		            }
		        }
			}
			//执行导入
			if(StringUtil.isNotNullOrBlank(busiTmptExportDto)){
				result = busiTmptService.insertBusiTmptExportDto(busiTmptTypeDictCode,busiTmptExportDto);
			}else{
				result.put("flag", false);
				result.put("msg", "导入模板为空");
				return result;
			}
		}catch(BaseException e) {
			e.printStackTrace();
			result.put("flag", false);
			result.put("msg", e.getMessage());
		}catch (Exception e) {
			e.printStackTrace();
			result.put("flag", false);
			result.put("msg", "导入失败!");
		}
		return result;
	

这里附上导入附件代码:

//导入附件
			for(AttachmentDto fileAttachmentDto:attachmentDtos){
				fileAttachmentDto.setBusiId(getNewId(fileAttachmentDto.getBusiId(),wordMap));
			}
			Set<Entry<String,Map<File,byte[]>>> entrySet = sourceFileMap.entrySet();
			for (Entry<String, Map<File, byte[]>> entry : entrySet) {
				String attachmentId = entry.getKey();
				Map<File, byte[]> value = entry.getValue();
				Set<Entry<File,byte[]>> entrySet2 = value.entrySet();
				for (Entry<File, byte[]> entry2 : entrySet2) {
					File file = entry2.getKey();
					byte[] bs = entry2.getValue();
					//调用方法,将文件保存到本地
					if(!file.exists()){
						getFile(bs, file);
					}
					fileMap.put(attachmentId, file);
					fileList.add(file);
					break;
				}
			}
			//保存附件并保存
			if(StringUtil.isNotNullOrBlank(attachmentDtos)){
				attachmentApi.transferAttachment("officeTab", attachmentDtos, fileMap);
			}
			//删除原有文件
			for(File file:fileList){
				delteFile(file);
			}
/** 
	 * 根据byte数组,生成文件 
	 */  
	public static void getFile(byte[] bfile, File file) {  
	      BufferedOutputStream bos = null;  
	      FileOutputStream fos = null;  
	      try {  
	    	  String path = file.getAbsolutePath();
	    	  path = path.substring(0, path.lastIndexOf("\\"));
	    	  File file2 = new File(path);
	    	  if (!file2.exists()) {  
	    		  file2.mkdirs();  
	          } 
	          fos = new FileOutputStream(file);  
	          bos = new BufferedOutputStream(fos);
	          bos.write(bfile);  
	       } catch (Exception e) {  
	           e.printStackTrace();  
	       } finally {  
	             if (bos != null) {  
	                 try {  
	                   bos.close();  
	                } catch (IOException e1) {  
	                     e1.printStackTrace();  
	                 }  
	             }  
	             if (fos != null) {
	                 try {
	                     fos.close();
	               } catch (IOException e1) {
	                 e1.printStackTrace();
	            }
	        }
	    }
	}
        private void delteFile(File file){
		//删除默认地址的文件
		//检查文件是否存在,如果不存在直接返回,不进行下面的操作
		if(!file.exists()){
			return;
		}
		//如果是文件删除,就删除文件,然后返回,不进行下面的操作
		if(file.isFile()){
			file.delete();
			return;
		}
	}

最后,这就可以了

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
序列化是将对象转换为字节流的过程,以便在网络上传输或保存到文件中。Java提供了ObjectOutputStreamObjectInputStream类来实现对象的序列化和反序列化。 要序列化一个对象,需要满足以下条件: 1. 对象必须实现Serializable接口。 2. 对象的所有成员变量都必须是可序列化的,即它们必须是基本类型、String类型或实现了Serializable接口的对象。 3. 对象的所有成员变量都必须是私有的。 下面是一个示例代码,演示如何序列化一个对象: ``` import java.io.*; public class SerializationDemo { public static void main(String[] args) { // 创建一个Person对象 Person person = new Person("张三", 20); try { // 创建一个ObjectOutputStream对象 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser")); // 序列化对象 oos.writeObject(person); // 关闭流 oos.close(); System.out.println("对象已经被序列化到person.ser文件中。"); } catch (IOException e) { e.printStackTrace(); } } } class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } ``` 在上面的代码中,我们创建了一个Person对象,并将其序列化到person.ser文件中。要序列化一个对象,我们需要创建一个ObjectOutputStream对象,并调用其writeObject()方法将对象写入文件中。注意,Person类必须实现Serializable接口,否则会抛出NotSerializableException异常。 反序列化一个对象也很简单,只需要创建一个ObjectInputStream对象,并调用其readObject()方法即可。下面是一个示例代码: ``` import java.io.*; public class DeserializationDemo { public static void main(String[] args) { try { // 创建一个ObjectInputStream对象 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser")); // 反序列化对象 Person person = (Person) ois.readObject(); // 关闭流 ois.close(); System.out.println("从person.ser文件中反序列化出的对象为:" + person.getName() + "," + person.getAge() + "岁。"); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们创建了一个ObjectInputStream对象,并调用其readObject()方法从person.ser文件中反序列化出一个Person对象。注意,我们需要将返回的Object对象强制转换为Person类型。如果文件中的对象类型与强制转换的类型不一致,会抛出ClassCastException异常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值