2013-03-18 51 views
0

我需要將郵件附件保存在utf8中。我嘗試這種代碼,但仍然有一些字符丟失:如何在utf8中保存郵件附件

public static void main(String args[]) throws Exception { 
    File emlFile = new File("example.eml"); 

    InputStream source; 

    source = new FileInputStream(emlFile); 

    MimeMessage message = new MimeMessage(null, source); 

    Multipart multipart = (Multipart) message.getContent(); 

    for (int x = 0; x < multipart.getCount(); x++) { 

     BodyPart bodyPart = multipart.getBodyPart(x); 
     String disposition = bodyPart.getDisposition(); 

     if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) { 
      System.out.println("Mail have some attachment : "); 

      DataHandler handler = bodyPart.getDataHandler(); 
      System.out.println("file name : " + handler.getName()); 


      //start reading inpustream from attachment 
      InputStream is = bodyPart.getInputStream(); 
      File f = new File(bodyPart.getFileName()); 
      OutputStreamWriter sout = new OutputStreamWriter(new FileOutputStream(f), "UTF8"); 
      BufferedWriter buff_out = new BufferedWriter(sout); 
      int bytesRead; 
      while ((bytesRead = is.read()) != -1) { 
       buff_out.write(bytesRead); 
      } 
      buff_out.close(); 

     } 
    } 
} 
+0

附件的內容/編碼是什麼? – 2013-03-18 14:30:53

+0

當我在txt編輯器中打開eml文件時,我只能看到:Content-Transfer-Encoding:base64,所以沒有編碼指定 – hudi 2013-03-18 14:33:54

回答

1

您正在閱讀從附件忽略任何編碼字節和輸出字符到文件中。你很可能會想做或者不混合這兩者。

如果附件包含原始字節,則對輸出進行UTF編碼並且您可以使用原始流是沒有意義的。

如果它包含文本,您還需要將附件讀取爲文本而不是原始字節,並使用編碼進行讀取和寫入。

在後一種情況下,

InputStream is = bodyPart.getInputStream(); 
InputStreamReader sin = new InputStreamReader(is, 
               "UTF8"); // <-- attachment charset 

File f = new File(bodyPart.getFileName()); 
OutputStreamWriter sout = new OutputStreamWriter(new FileOutputStream(f), "UTF8"); 
BufferedReader buff_in = new BufferedReader(sin); 
BufferedWriter buff_out = new BufferedWriter(sout); 

int charRead; 
while ((charRead = buff_in.read()) != -1) { 
    buff_out.write(charRead); 
} 

buff_in.close(); 
buff_out.close(); 
相關問題