解決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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章