首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

转码utf-8仍是gbk

2012-10-31 
转码utf-8还是gbk?说今天写这一篇,因为遇到个问题,在centos上导出文件一直乱码。原来就没出现这问题,适了好

转码utf-8还是gbk

?说今天写这一篇,因为遇到个问题,在centos上导出文件一直乱码。

原来就没出现这问题,适了好多种方法。

最后把导出的编码设成gbk竟然好了。现在还不知其原因,如有高手还请赐教。

?

java代码编码utf-8,

jsp编码utf-8,

centos中i18n:utf-8,

tomcat:uriencoding utf-8.

?

?

?

?public static String toUtf8String(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);
??? }

?

?

对于UTF-8编码格式的文本文件,其前3个字节的值就是-17、-69、-65,所以,判定是否是UTF-8编码格式的代码片段如下

?? 测试文件编码是否为UTF-8

???? File file = new File(path);

???? InputStream ios = new java.io.FileInputStream(file);

????te[] b = new byte;

???? ios.read(b);

???? ios.close();

???? if (b[0] == -17 && b[1] == -69 && b == -65)

?????? System.out.println(file.getName() + “:编码为UTF-8″);

???? else

?????? System.out.println(file.getName() + “:可能是GBK,也可能是其他编码。”);

?

?

?? public static void downloadFile(HttpServletRequest request,
??????????? HttpServletResponse response, String fileName)
??? {
??????? if (StringUtils.isEmpty(fileName))
??????? {
??????????? return;
??????? }

??????? //导出文件路径
??????? String filePath = PlatformConfig.getUseDataPath() + Constants.EXPORT_PATH + fileName;
???????
??????? // 处理中文名称,需要编码
??????? response.setContentType("application/octet-stream; CHARSET=GBK");
???????
??????? InputStream inputStream = null;
??????? OutputStream outputStream = null;
??????? try
??????? {
??????????? response.setHeader("Content-Disposition", "attachment; filename="
??????????? ??+ EncodingUtil.getString(fileName.getBytes("gbk"),
?? ???? "ISO8859-1"));
??????????? inputStream = new FileInputStream(filePath);
??????????? outputStream = response.getOutputStream();
???????????
??????????? transferFile(inputStream, outputStream);
??????? }
??????? catch (FileNotFoundException e)
??????? {
??????????? logger.error(e.toString());
??????? }
??????? catch (IOException e)
??????? {
??????????? logger.error(e.toString());
??????? }
??????? finally
??????? {
??????????? try
??????????? {
??????????????? if (inputStream != null)
??????????????? {
??????????????????? inputStream.close();
??????????????? }
??????????? }
??????????? catch (Exception e)
??????????? {
??????????????? logger.error(e.toString());
??????????? }
??????????? try
??????????? {
??????????????? if (outputStream != null)
??????????????? {
??????????????????? outputStream.close();
??????????????? }
??????????? }
??????????? catch (Exception e)
??????????? {
??????????????? logger.error(e.toString());
??????????? }
???????????
??????????? //删除临时导出文件
??????????? FileTools.delFile(filePath);
??????? }
??? }
???

热点排行