I am creating a mail client using the JavaMail API. Everything works fine, since I can connect to the mail server (using IMAP), delete mail, receive received letters and show them to the user, etc.
Now the problem is when it comes to downloading PDF attachments. PDF files do not load completely ... some files are missing.
If any PDF attachment is 38 KB in size when downloading the attachment using IE or any other web browser, but when I download it using my java code, it has a size of 37.3 Kb. It is not complete. Therefore, when I try to open it using Adobe Reader, the error message "File is corrupted ..."
Here is the code I wrote to download the attachment:
public boolean saveFile(String filename,Part part) throws IOException, MessagingException { boolean ren = true; FileOutputStream fos = null; BufferedInputStream fin = null; InputStream input = part.getInputStream(); File pdffile = new File("d:/"+filename); try{ if(!pdffile.exists()){ fos = new FileOutputStream(pdffile); fin = new BufferedInputStream(input); int size = 512; byte[] buf = new byte[size]; int len; while ( (len = fin.read(buf)) != -1 ) { fos.write(buf, 0, len); } input.close(); fos.close(); }else{ System.out.println("File already exists"); } }catch(Exception e ){ ren = false; } return ren; }
Am I missing something? Any helpful help is appreciated.
source share