100分:关于如何解决邮件附件名称乱码问题(另贴给分,这个请放心)
kw123 2004-08-26 01:07:19 不知道什么原因?附件的名称老是出现中文乱码!如何处理和解决!100分
在http://community.csdn.net/Expert/topic/3290/3290875.xml?temp=.6617395中加
if ((temp = part.getFileName()) != null)
{
String filename="";
filename = new String(MimeUtility.decodeText(part.getFileName()).getBytes("ISO8859_1"),"GBK");
filename=new String(filename.toLowerCase().getBytes("ISO8859_1"),"GBK");
savePart(part,filename);//
s2= "<b>附件:</b><a href=fujian/"+filename+"> " + filename + "</a><br>";
}
public void savePart(Part part,String Filename)
{
try
{
Filename =new String(Filename.getBytes("ISO8859_1"),"GBK");
File file = new File("D:\\youjian\\MailWeb\\fujian\\"+Filename);
if(file.exists()==true) return;
for(int i=0;file.exists();i++){
int d = Filename.lastIndexOf(".");
String tmp = Filename.substring(0,d-1) + i + Filename.substring(d,Filename.length());
Filename=tmp;
file = new File("D:\\youjian\\MailWeb\\fujian\\"+Filename);
}
FileOutputStream myFileoutputstream = new FileOutputStream(file);
int chunk = part.getSize();
byte [] buffer = new byte[chunk];
InputStream instream = part.getInputStream();
instream.read(buffer,0,chunk);
myFileoutputstream.write(buffer,0,chunk);
instream.close();
myFileoutputstream.close();
}
catch(Exception e)
{
//out.print("无");
}
}
找到一篇文章
但是有一种情况下,取得的中文文件名也是乱码,原因有的邮件服务器在发送邮件时,对附件名进行了特殊的编码,解决如上问题的方法如下:
首先:
1)用如上的方法取得中文文件名:
String filename= new String(getISOFileName(part).getBytes("ISO-8859-1"),"gb2312");
然后创建文件,如果发生FileNotFoundException异常,说明取得的文件名是经过特殊编码的--我们取得到的未解码的,是乱吗,那么就要用javamail提供的函数decodeText进行解码。具体方法如下。
try{
myFileoutputstream= new FileOutputStream(filename);
}catch(FileNotFoundException fe){
try{
if (filepath.exists()){
filename = new File(filepath,MimeUtility.decodeText(getISOFileName(part)));
}catch(Exception e){
System.out.println("getpart(int i)重新生成文件:"+e.toString());
}
}catch(Exception e){
System.out.println("getpart(int i)重新生成文件:"+e.toString());
}
}
经过如上步骤,就能彻底解决javamail附件中文名乱码问题了。
可是我看的不是很懂!
请高手解释一下
如何处理以上的问题