将图像附加到调度程序作业类中的类路径资源时出错

时间:2013-08-16 06:29:53

标签: java spring quartz-scheduler

protected void executeInternal(JobExecutionContext context) throws JobExecutionException 
{
  System.out.println("Sending Birthday Wishes... ");

   try
   {
            for(int i=0;i<maillist.length;i++)
            {   


            Email email = new Email();
            email.setFrom("spv_it@yahoo.com");
            email.setSubject("Happy IndependenceDay");
            email.setTo(maillist[i]);

            email.setText("<font color=blue><h4>Dear Users,<br><br><br>Wish you a Happy Independence Day!<br><br><br>Regards,<br>Penna Cement Industries Limited</h4></font>");
            byte[] data = null;
            ClassPathResource img = new ClassPathResource("newLogo.gif");
            InputStream inputStream = img.getInputStream();
            data = new byte[inputStream.available()];
            while((inputStream.read(data)!=-1));

            Attachment attachment = new Attachment(data, "HappyBirthDay","image/gif", true);
            email.addAttachment(attachment);

            emailService.sendEmail(email);
        }


   }
   catch (MessagingException e)
   {
    e.printStackTrace();
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }

 }

这是我得到的错误:

java.io.FileNotFoundException: class path resource [newLogo.gif] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:135)
at com.mail.schedular.BirthdayWisherJob.executeInternal(BirthdayWisherJob.java:55)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:66)
at org.quartz.core.JobRunShell.run(JobRunShell.java:223)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)

3 个答案:

答案 0 :(得分:0)

最佳做法是通过提及该文件的绝对路径来读取/写入或提供任何文件的引用。 对于您的问题,它显示 FileNotFoundException ,因为JVM无法在当前目录中找到该文件,默认情况下是您的源路径。因此,在 ClassPathResource 中提供绝对路径,或将该图像文件复制到当前目录。它会解决你的问题。

答案 1 :(得分:0)

我认为您需要将文件放在src文件夹中,如果有,请检查它是否位于src目录中的某个目录下。

然后给出正确的位置,如下面给出的详细信息 SRC [DIR] -----&GT; newLogo.gif

ClassPathResource img = new ClassPathResource("newLogo.gif");

,或者 SRC [DIR] -----&GT;图像[目录] ----&GT; newLogo.gif

ClassPathResource img = new ClassPathResource("/images/newLogo.gif");

答案 2 :(得分:0)

由于作业在单独的石英线程中运行,因此出现此错误,我建议您将文件 newLogo.gif 放在罐子外面,然后使用以下文件进行加载。 Thread.currentThread().getContextClassLoader().getResource("classpath:image/newLogo.gif");