Java 怎么写入httpservletresponse

2019年8月17日22:01:47 评论 23

1.简介

Java 怎么写入httpservletresponse?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.http.HttpServletResponse;

public class Main{
    public static void writeToResponse(HttpServletResponse response,
            File file, String fileName) {
        response.reset();
        if (file == null) {
            return;
        }
        BufferedOutputStream outx = null;
        FileInputStream fileIn = null;
        try {
            outx = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + gbToUtf8(fileName));

            if (file.exists()) {
                fileIn = new FileInputStream(file);
                int len = (int) file.length();
                if (fileIn != null) {
                    byte[] html = new byte[len];
                    while ((len = fileIn.read(html)) != -1) {
                        outx.write(html, 0, len);
                    }
                }
            }
            outx.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileIn != null)
                    fileIn.close();
                if (outx != null)
                    outx.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (file.exists()) {
                try {
                    file.delete();
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    file.deleteOnExit();
                }
            }
        }
    }
    public static String gbToUtf8(String src) {
        byte[] b = src.getBytes();
        char[] c = new char[b.length];
        for (int i = 0; i < b.length; i++) {
            c[i] = (char) (b[i] & 0x00FF);
        }
        return new String(c);
    }
}

 

3.总结

示例代码演示了 Java 怎么写入httpservletresponse,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: