0

I found many of create a tmp file with specific name, but no question about create tmp folder.

I want to create a folder with specific name which has no random number.

Is it possible to do it?

Litchy
  • 623
  • 7
  • 23
  • Did you see the [createTempDirectory](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createTempDirectory-java.nio.file.Path-java.lang.String-java.nio.file.attribute.FileAttribute...-) method? – Thiyagu Nov 20 '20 at 06:30
  • If you didn't have the "without random number" requirement then `Files#createTempDirectory(...)` would be perfect for you. – Slaw Nov 20 '20 at 06:34
  • @Slaw yes, in that case no question is needed to open – Litchy Nov 20 '20 at 06:35
  • I'm not sure there's really anything special about temporary directories or files, other than their designated location. You can get the system's temporary directory by querying the `java.io.tempdir` system property. Then you should be able to create directories with the names you want via `Files#createDirectory(...)`. The reason for the random number is to make name collisions less likely. But I could be mistaken and temp dirs/files are handled specially. – Slaw Nov 20 '20 at 06:38
  • @OldProgrammer the key word here is tmp, I want this dir to be removed as JVM close. – Litchy Nov 20 '20 at 06:38
  • @Slaw I could share my use case here. I want to create a tmp dir used by environment variable. But the environment variable should be set before JVM run so read it in code does not work here. – Litchy Nov 20 '20 at 06:40
  • You can query environment variables in code via `System#getenv()` and `System#getenv(String)`. – Slaw Nov 20 '20 at 06:43
  • What distinguishes a _temporary_ folder from a regular folder? – Abra Nov 20 '20 at 06:45
  • @Slaw The need is to set environment variable, not query. If I could set it in code, then I could get the tmp dir random name and use it. – Litchy Nov 20 '20 at 06:47
  • @Abra It is removed with JVM shutdown. – Litchy Nov 20 '20 at 06:48
  • Ah. Well, that's the opposite of "_But the environment variable should be set before JVM run so read it in code does not work here_" as I interpreted it. – Slaw Nov 20 '20 at 06:48
  • @Slaw Sorry for misleading, should be "But the environment variable should be set before JVM run so read the tmp dir it in code and set environment variable after this does not work here" – Litchy Nov 20 '20 at 06:49
  • 1
    [shutdown hook](https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#addShutdownHook-java.lang.Thread-) ? – Abra Nov 20 '20 at 06:50
  • @Abra Yes, shutdown hook is backup.. Seems I have to use it. – Litchy Nov 20 '20 at 06:55
  • Even `java.io.File#deleteOnExit()` uses a shutdown hook for the implementation. And the documentation of both `java.nio.file.Files#createTempFile(...)` and `java.nio.file.Files#createTempDirectory(...)` mention using shutdown hooks to delete the files when the JVM exits. – Slaw Nov 20 '20 at 07:00

0 Answers0