ITeye博客

struts 大量文件读取的问题,因为访问量大,而且文件也大,总是内存溢出。

bluesummer · 2009-11-07 08:55 · struts相关 · 编程语言 · Markdown

struts 大量文件读取的问题,因为访问量大,而且文件也大(很多都是几十M上百M),总是内存溢出。 唉!头痛死了,一小段代码改了又改,还是总内存溢出。 我的代码如下:


	public static boolean readFile(HttpServletResponse response,
			String filePath, String fileLoc, String fileName){
		ServletOutputStream sos = null;
		File myFile = null;
		InputStream is = null;
		myFile = new File(filePath + fileLoc);
		if(myFile==null || myFile.length()<1) {
			return false;
		}
		response.setContentType("application/octet-stream;charset=utf-8");
		response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
		try {
			sos = response.getOutputStream();
			is = new FileInputStream(myFile);
			int blobsize = (int) myFile.length();
			byte[] blobbytes = new byte[blobsize];
			int bytesRead = 0;
			while ((bytesRead = is.read(blobbytes)) != -1) {
				sos.write(blobbytes, 0, bytesRead);
			}
			sos.flush();
			sos.close();
			is.close();
		}catch (Exception ex) {
			System.out.println(ex);
			try {
				myFile = null;
				sos.close();
				sos = null;
				is.close();
				is = null;
			}catch(IOException e) {
				e.printStackTrace();
			}
			return false;
		} finally {
			try {
				if(is!=null) {
					myFile = null;
					sos.close();
					sos = null;
					is.close();
					is = null;
				}
			}catch(IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

请大家帮忙分析一下,万分感谢!

评论(5)

  1. #5 楼 · bluesummer · 2011-06-18 16:39

    超级潜水员 writes:

    服了博主,缓冲区要固定大小,晕!!! 一菜鸟

    请问我如何解决啊?我真是菜鸟一个。 :oops:

  2. #4 楼 · 绿生2009 · 2009-11-09 16:50

    这个算不算 PermGen Space OutOfMemory,需要另外设定JAVA_OPTS环境变量来改变缓存大小?

  3. #3 楼 · tuoxie007 · 2009-11-08 14:09

    缓存固定大小,读一点写一点

  4. #2 楼 · 超级潜水员 · 2009-11-07 12:48

    服了博主,缓冲区要固定大小,晕!!! 一菜鸟

  5. #1 楼 · mycybyb · 2009-11-07 11:53

    int blobsize = (int) myFile.length();
    byte blobbytes = new byte;

    这两句就注定要出问题。

评论功能维护中,当前仅展示历史评论。