【问题标题】:create a temporary file with a specified name in java在java中创建一个具有指定名称的临时文件
【发布时间】:2017-06-07 10:35:48
【问题描述】:

我有一个 Byte[] 数组,我想把它的内容放到一个临时文件中。

我尝试过这样做

try {
            tempFile = File.createTempFile("tmp", null);
            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write(sCourrier.getBody());
        } catch (IOException e) {
            e.printStackTrace();
        }

但我希望我自己指定文件名,而不是由 jvm 生成

【问题讨论】:

  • 您可以创建一个常规文件并确保在完成后将其删除。这样,您可以随意命名它。您仍然可以使用临时目录 System.getProperty("java.io.tmpdir")
  • @domdom 将其添加为答案
  • 临时文件的目的之一是确保您获得一个唯一命名的文件,这样您就不会意外覆盖其他程序的临时文件,也不会有其他程序意外覆盖您的临时文件。为临时文件指定特定名称会破坏这种保护。您要克服的真正问题是什么?
  • @KevinAnderson 我想在我的 jsp 上的一个嵌入标签 <embed src="" > 上显示文件,所以我需要有他的名字的文件
  • 然后查看我的评论和/或gati's answer。但是,我建议还确保没有同名的临时文件。您可以通过在文件名中使用时间戳轻松实现此目的。

标签: java arrays temporary-files


【解决方案1】:

你可以直接给出位置和文件名或者你可以访问本地文件系统并找到临时目录

 String tempDir=System.getProperty("java.io.tmpdir");

您可以使用临时目录和自定义文件名。

public static void main(String[] args) {
    try {
        String tempDir=System.getProperty("java.io.tmpdir");
        String sCourrier ="sahu";
        File file = new File(tempDir+"newfile.txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(sCourrier.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }

【讨论】:

    【解决方案2】:

    你可以使用番石榴Files.createTempDir():

    File file = new File(Files.createTempDir(), fileName.txt);

    但由于 API 已被弃用,他们还建议使用带有更多参数的 Nio:

    Path createTempDirectory(String prefix, FileAttribute<?>... attrs)

    所以如果你自己有一个方法会更好:

    File createTempFile(String fileName, String content) throws IOException {
            String dir = System.getProperty("java.io.tmpdir");
            File file = new File(dir + fileName);
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(content.getBytes(StandardCharsets.UTF_8));
            }
            return file;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      相关资源
      最近更新 更多