项目采用UTF-8作为统一的编码(JVM中缺省字符集、Tomcat的URIEncoding字符集、Struts2的Locale字符集配置、过滤器字符集、页面统一编码、数据库编码、mysql数据库连接字符集等),基本上排除了日常开发的中文乱码问题,具体可以参考Struts2中Datetimepicker控件的中文问题。
但在处理资源下载时候,由于资源在Linux服务器上存放目录及文件名称都存在中文(例如/products/material/img/101×80/人物肖像101×8/测试.jpg),因此在下载时候会报告FileNotFoundException错误,实际上仍然为中文文件名称问题,现简单总结一下处理方案:
分析思路:操作系统缺省字符集设置为zh_CN.UTF-8,JVM在存取操作系统文件时候,实际上要调用Linux操作系统本身的I/O函数来处理,而Linux的I/O函数存取中文文件时候字符集是由操作系统的环境变量决定的,因此报FileNotFoundException,应该是环境变量问题。
解决方案:将Linux操作系统本身缺省编码及字符集设为zh_CN.GB18030,这样可以正常处理中文名称。但在与JVM、数据库等相关的地方的字符集仍然采用UTF-8字符集。
备注:实际上并不需要将操作系统全局环境变量设置为zh_CN.GB18030,可以只设置运行Tomcat、Jboss的用户的环境变量,但考虑到方便性,直接设置全局的操作系统环境变量。
1、修改/etc/sysconfig/i18n
LANG=”zh_CN.GB18030″
LANGUAGE=”zh_CN.GB18030:zh_CN.GB2312:zh_CN”
SUPPORTED=”zh_CN.UTF-8:en_US.UTF-8:en_US:en:zh_CN.GB18030:zh_CN:zh:zh_TW.big5:zh_TW:zh:ja_JP.UTF-8:ja_JP:ja:ko_KR.eucKR:ko_KR:ko”
SYSFONT=”latarcyrheb-sun16″
SYSFONTACM=”8859-15″
2、设置环境变量
在/etc/profile中设置
export LC_ALL=zh_CN.GB18030
export LANG= zh_CN.GB18030
3、重启服务器
4、测试代码
<%@ page import=”java.io.*,java.net.*”%>
<%@ page language=”java” pageEncoding=”UTF-8″ contentType=”text/html;charset=UTF-8″ %>
<html>
<head>
<title>中文下载测试代码</title>
<meta http-equiv=”pragma” content=”no-cache”>
<meta http-equiv=”cache-control” content=”no-cache”>
<meta http-equiv=”expires” content=”0″>
<meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
<meta http-equiv=”description” content=”This is my page”>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
</head>
<body>
<%
String filename = “/root/技术中心周报20080906(梁川).doc”;
String filename1=”技术中心周报20080906(梁川).doc”;
OutputStream outputStream = null;
InputStream inputStream = null;
try{
File file = new File(filename);
response.reset();
response.setContentType(“application/octet-stream; charset=UTF-8”);
long filelength = file.length();
response.setHeader(“Cache-Control”, “content=\”no-store\””);
response.setHeader(“Content-Disposition”, “attachment; filename=” + new String(filename1.getBytes(“GBK”),”ISO8859-1″));
response.setContentLength((int)filelength);
outputStream = response.getOutputStream();
inputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int i = -1;
while ((i = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
outputStream.flush();
}catch(Exception e){
}finally{
if(outputStream != null){
outputStream.close();
outputStream = null;
}
if(inputStream != null){
inputStream.close();
inputStream = null;
}
}
%>
</body></html>
备注:这是很久以前写的邮件了,懒得写、懒得整理,只是在用imagemagick 处理缩略图时候又遇见中文目录及中文文件名的问题,因此翻出来整理一下,供备查。
转载请注明:出家如初,成佛有余 » Linux环境下资源下载中文目录及中文文件名称问题