What's the best way of creating a large temporary file in Java, and being sure that it's on disk, not in RAM somewhere?
If I use
Path tempFile = Files.createTempFile("temp-file-name", ".tmp");
then it works fine for small files, but on my Linux machine, it ends up being stored in /tmp
. On many Linux boxes, that's a tmpfs filesystem, backed by RAM, which will cause trouble if the file is large. The appropriate way of doing this on such a box is to put it in /var/tmp
, but hard-coding that path doesn't seem very cross-platform to me.
Is there a good cross-platform way of creating a temporary file in Java and being sure that it's backed by disk and not by RAM?
There is no platform-independent way to determine free disk space. Actually there is not even a good platform-dependent way; things that happen are zfs filesystems (which may be compressing your data on the fly), directories that are being filled by other applications, or network shares that are simply lying to you.
I know of these options:
$XDG_CACHE_HOME
for the cache; the cache directory is supposed to be nice and big (take a look at the~/.cache/
of anybody using a Linux machine). On Windows, you'd simply use%TEMP%
but that's okay because%TEMP%
is supposed to be big anyway.This gives the following strategy: Try environment variables, first
XDG_CACHE_HOME
(if it's nonempty, it's a Posix system with XDG conventions), thenTMP
(if it's nonempty, it's a Posix system and you don't have a better option than/tmp
anyway), finallyTEMP
in case it's Windows.