简体   繁体   English

为什么我不能使用toString解析javamail附件?

[英]Why can't I parse a javamail attachment using toString?

It seems to me the snippet below should work, but "mp.getBodyPart(1).getContent().toString()" returns 在我看来下面的片段应该工作,但“mp.getBodyPart(1).getContent()。toString()”返回

com.sun.mail.util.BASE64DecoderStream@44b07df8 com.sun.mail.util.BASE64DecoderStream@44b07df8

instead of the contents of the attachment. 而不是附件的内容。

public class GMailParser {
    public String getParsedMessage(Message message) throws Exception {
        try {
            Multipart mp = (Multipart) message.getContent();
            String s = mp.getBodyPart(1).getContent().toString();
            if (s.contains("pattern 1")) {
                return "return 1";
            } else if (s.contains("pattern 2")) {
                return "return 2";
            }
            ...

It simply means that the BASE64DecoderStream class does not provide a custom toString definition. 它只是意味着BASE64DecoderStream类不提供自定义toString定义。 The default toString definition is to display the class name + '@' + Hash Code, which is what you see. 默认的toString定义是显示类名+'@'+ Hash Code,这就是你所看到的。

To get the "content" of the Stream you need to use the read() method. 要获取Stream的“内容”,您需要使用read()方法。

This parses BASE64DecoderStream attachments exactly as needed. 这将根据需要完全解析BASE64DecoderStream附件。

private String getParsedAttachment(BodyPart bp) throws Exception {
    InputStream is = null;
    ByteArrayOutputStream os = null;
    try {
        is = bp.getInputStream();
        os = new ByteArrayOutputStream(256);
        int c = 0;
        while ((c = is.read()) != -1) {
            os.write(c);
        }
        String s = os.toString(); 
        if (s.contains("pattern 1")) { 
            return "return 1"; 
        } else if (s.contains("pattern 2")) { 
            return "return 2"; 
        } 
        ... 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM