【问题标题】:how to create temp file without random number [duplicate]如何创建没有随机数的临时文件[重复]
【发布时间】:2018-07-21 07:47:03
【问题描述】:

我需要将 pdf 文件作为邮件附件发送。这是每 2 小时运行一次的调度程序作业。直接它不会给出 File Not Found Exception 所以我想我把它放在临时目录并从那里发送。该作业在 JBoss 服务器上运行。

File temp = null;
String tDir = System.getProperty("java.io.tmpdir") + "SupplierGuide";try
{
    temp = File.createTempFile(tDir, ".pdf");
    final InputStream inputStream = SendNotificationToContacts.class.getClassLoader()
            .getResourceAsStream(result.getProperty("supplier.guide"));

    IOUtils.copy(inputStream, new FileOutputStream(temp));
}catch(
Exception e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

【问题讨论】:

  • 我想要文件名“SupplierGuide.pdf”。
  • 你从哪里得到一个随机数?
  • 你为什么不直接取你想要的文件名呢? (temp = new File("whatever name you want");) 顺便说一句。有趣的代码格式化方法。
  • 实际上第一个问题是......我在服务器上得到 java.io.FileNotFoundException 而在本地调试它工作正常。我有一个 PDF 文件,它是 jar 本身的一部分。此 PDF 将通过邮件发送。这个 jar 将通过 kjb 作业在服务器上运行。
  • 为了解决第一个问题,我创建了临时文件。现在名称有随机数。

标签: java


【解决方案1】:

我从一个 servlet 在 Apache Tomcat 7.0.65 Web 服务器上尝试了这个。此例程还使用 Java 7 和 Apache Commons IO Utils (commons-io-1.3.2.jar)。

private void createUserGuideInTempFolder()
        throws IOException {
    String inputFileName = "N:\\TestData\\user-guide.pdf";
    String baseName = FilenameUtils.getBaseName(inputFileName);
    String extension = FilenameUtils.getExtension(inputFileName);
    Path tempFilePath = Files.createTempFile(baseName, extension);
    Path inputFilePath = Paths.get(inputFileName);

    InputStream inStream = Files.newInputStream(inputFilePath);
    byte [] fileBytes = IOUtils.toByteArray(inStream);
    tempFilePath = Files.write(tempFilePath, fileBytes);
    System.out.println(inputFilePath);
    // Prints input file: N:\TestData\user-guide.pdf
    System.out.println(tempFilePath);
    // Prints temp file: N:\apache-tomcat-7.0.65\temp\user-guide3642635958536288074pdf

    Path newTempFilePath = Paths.get(tempFilePath.getParent().toString(),
                    inputFilePath.getFileName().toString());    
    newTempFilePath = Files.move(tempFilePath, newTempFilePath);
    System.out.println(newTempFilePath);
    // Prints result file in temp: N:\apache-tomcat-7.0.65\temp\user-guide.pdf
}

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多