Using ServletOutputStream to write very large files in a Java servlet without memory issues

后端 未结 10 1738
太阳男子
太阳男子 2020-12-01 00:28

I am using IBM Websphere Application Server v6 and Java 1.4 and am trying to write large CSV files to the ServletOutputStream for a user to download. Files are

10条回答
  •  误落风尘
    2020-12-01 00:55

    I have used a class that wraps the outputstream to make it reusable in other contexts. It has worked well for me in getting data to the browser faster, but I haven't looked at the memory implications. (please pardon my antiquated m_ variable naming)

    import java.io.IOException;
    import java.io.OutputStream;
    
    public class AutoFlushOutputStream extends OutputStream {
    
        protected long m_count = 0;
        protected long m_limit = 4096; 
        protected OutputStream m_out;
    
        public AutoFlushOutputStream(OutputStream out) {
            m_out = out;
        }
    
        public AutoFlushOutputStream(OutputStream out, long limit) {
            m_out = out;
            m_limit = limit;
        }
    
        public void write(int b) throws IOException {
    
            if (m_out != null) {
                m_out.write(b);
                m_count++;
                if (m_limit > 0 && m_count >= m_limit) {
                    m_out.flush();
                    m_count = 0;
                }
            }
        }
    }
    

提交回复
热议问题