解决response.getOutputStream()输出页面txt文本中文乱码

几天公司要求做一个附件预览的需求,txt在线预览,已流的形式输出到页面,一直显示中文乱码,后来尝试res.setContentType(“text/plain;charset=utf-8”);还是不行,将charset="utf-8"改成charset="iso8859-1"依然不行,最后直接将其设置成gb2312
,奇迹出现了,不乱吗了,多尝试一下,肯定可以的,下面上一段代码:

这里是引用
public void openOtherTxt(HttpServletRequest request,HttpServletResponse res)throws Exception{
String path = request.getParameter(“path”);
path = URLDecoder.decode(path,“UTF-8”);
byte[] bdata = fileToBytes(path);
res.reset();
//res.setCharacterEncoding(“UTF-8”);
res.setContentType(“text/plain;charset=gb2312”);
if(bdata!=null){
OutputStream op;
try {
op = res.getOutputStream();
op.write(bdata);
op.close();
if (op.equals(null)) {
res.flushBuffer();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private byte[] fileToBytes(String path){
byte[] buffer = null;
File file = new File(path);

    FileInputStream fis = null;
    ByteArrayOutputStream bos = null;

    try {
        fis = new FileInputStream(file);
        bos = new ByteArrayOutputStream();

        byte[] b = new byte[1024];

        int n;

        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        
        buffer = bos.toByteArray();
    } catch (FileNotFoundException ex) {
    	ex.printStackTrace();
    } catch (IOException e) {
    	e.printStackTrace();
    }
    return buffer;
}

你可能感兴趣的:(java)