【问题标题】:JAVA - getBytes return UTF-8 without BOMJAVA - getBytes 返回没有 BOM 的 UTF-8
【发布时间】:2015-08-27 13:39:00
【问题描述】:

我以这种方式通过电子邮件发送一个txt文件。文件的数据在 StringBuffer 中。

文件构造:

StringBuffer lBufferFinal = new StringBuffer();
// Put some text in lBufferFinal
FichierByteVO lFichier = new FichierByteVO();
    lFichier.setFileName("Statistic.txt");
    lFichier.setMIMEType("text/plain");
    lFichier.setFile(lBufferFinal.toString().getBytes(Charset.forName("UTF-8")));

在电子邮件中添加文件:

MimeMessage lMessage = new MimeMessage(lSession);
// Do thing tu put sender, receiver, subject etc to the MimeMessage
Multipart = new MimeMultipart();
BodyPart lMessageBodyPart = new MimeBodyPart();
lMessageBodyPart.setText("Here is an email !");
lMultipart.addBodyPart(lMessageBodyPart);
lMessageBodyPart = new MimeBodyPart();
DataHandler lDataHandler = new DataHandler(new ByteArrayDataSource(lFichier.getFile(), lFichier.getMIMEType()));
        lMessageBodyPart.setDataHandler(lDataHandler);
                    lMessageBodyPart.setFileName(lFichier.getFileName());
        lMultipart.addBodyPart(lMessageBodyPart);
    }
    lMessage.setContent(lMultipart);

我通过电子邮件收到的文件在 notepad++ 或 excel(不识别重音符号)中默认打开为“UTF-8 without BOM”。

所以我需要用excel打开,所以要有带有BOM编码的UTF-8。

你有什么建议吗?

【问题讨论】:

  • 您可以添加 BOM,但默认行为是不包含它。大多数工具在使用 UTF-8 编码时不会编写 BOM。您需要将 notepad++ 设置为默认读取 UTF-8。

标签: java excel utf-8 character-encoding


【解决方案1】:

不方便使用 BOM。你可以把邮件的编码这样:

JavaMailSenderImpl mailer = new JavaMailSenderImpl();
...
mailer.setDefaultEncoding("ISO-8859-1");

这将识别重音

【讨论】:

  • 我使用的是 Transport.send 来发送邮件,而不是 MailSender
  • 这是安静的不理解......如果我使用 ISO-8859-1 对文件进行编码,Excel 无法识别 ;字符作为列分隔符...
【解决方案2】:

最后,我使用 .CSV 扩展名和 ISO-8859-1,效果很好!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-18
    • 2012-11-14
    • 1970-01-01
    • 2014-03-10
    • 2016-05-04
    • 2018-02-28
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多