使用对象流时产生了EOFException异常

在写一个监听器更新当前页面访问浏览次数时,因为需要在服务器停止时将浏览次数保存在文件中,方便下次调用。

为了保存多个页面的数据,使用了Map集合。保存的时候经过检查文件,可以确定没有发生任何错误,但是在重启TOMCAT时,始终会产生一个EOFException异常,无法读取到任何内容。

经过各种反复尝试、修改、删除都无法解决,百度了许多也似乎跟这个都没多大关系。然后因为下课放学,所以就此作罢,等待下个星期一询问老师。

然后今天想起来这个错误,总觉得心里不太舒服,犹豫了还是继续尝试修改正确,又是一番修改和百度,最后终于在一个CSDN博客中找到了解决办法,尝试后完美运行。

具体错误就是因为我先初始化了ObjectOutputStream对象,再初始化ObjectInputStream对象,但是它俩不是在用一个方法中调用各自相关的方法,所以一直引发该错误。在该博客一个截图是这样说的:è¿éåå¾çæè¿°然后检查了一下我的代码,确实是先初始化的ObjectOutputStream对象,同时服务器第二次启动时是先运行的readObject()方法,因此会产生EOFException异常。

修改后代码如下:

private int count;
	private Map<String,Integer> map = new HashMap<>();
	private File file;
    public CountListener() {
    	file = new File("h:/map.txt");
    }

    public void requestInitialized(ServletRequestEvent sre)  { 
    	HttpServletRequest request = (HttpServletRequest)(sre.getServletRequest());
    	HttpSession session = request.getSession();
    	ServletContext application = request.getServletContext();
    	
    	if( request.getServletPath().contains(".jsp")) {
	    	String pageURI = request.getServletPath().substring(1, request.getServletPath().lastIndexOf("."));
	    	
	    	if(!map.containsKey(pageURI)){
	    		map.put(pageURI, 0);
	    	}
	    	count = map.get(pageURI);
	    	long nowTime = System.currentTimeMillis();
	    	long befTime = nowTime;
	    	if(session.getAttribute(pageURI)!=null) {
	    		befTime = (long) session.getAttribute(pageURI);
	    	}
	    	if((nowTime-befTime)==0||(nowTime-befTime)>=(1000*10)) {
	    		count++;
	    	}
	    		session.setAttribute(pageURI,nowTime);
	    		application.setAttribute(pageURI, count);
	    		map.put(pageURI, count);
    	}
    }
    
    //生命周期---application
    public void contextInitialized(ServletContextEvent sce)  { 
    	try {
    		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
    		if(map instanceof Object) {
    			map = (Map<String, Integer>) ois.readObject();
    		}
    		ois.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (EOFException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
    }
    public void contextDestroyed(ServletContextEvent sce)  { 
    	try {
    		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(map);
			oos.flush();
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值