简体   繁体   中英

What is the best windows equivalent for /tmp?

I want to improve the cross platform behavior of a java application. However, its test suite currently assumes the existence of the /tmp directory.

What is the best equivalent location on the windows platform? NB I most definitely do not want to assume the user has admin rights but I do want it to work on at least XP, Vista & Windows7.

Is there an existing environment variable that would help, and/or a set of preferred locations I could try in order of preference?

The system property java.io.tmpdir can be used for the user's temp directory:

File tmp = new File(System.getProperty("java.io.tmpdir"));

This may be preferred over File.createTempFile (which, in any case, uses the tmpdir system property under the hood) in the instance where you want to search for temp files (for example, cached data from a previous invocation of your application, which sounds like it might be the case from your question).

You can change the value of the system property by providing a runtime override on the command line (a JVM argument): -Djava.io.tmpdir=C:\\foo\\bar

Note: the "trailing slash" issue descibed in the comments to seth 's answer below can be avoided by using the relevant File constructor:

String fileName = "foobar.txt"
String tmpPath = System.getProperty("java.io.tmpdir");
File tmpFile;
tmpFile = new File(tmpPath + File.separator + fileName); //possible problem
tmpFile = new File(new File(tmpPath), fileName); //OK!

Obviously windows also has an DOS environment variable %TEMP% which could be used from any scripts which you have

为什么不使用java.io.File.createTempFile()

Windows定义了环境变量TEMP和TMP,它们都给出了当前用户的临时文件夹。

使用File.createTempFile("myPrefix","mySuffix")

如果您想坚持做一些特定于Windows的事情,可以使用%temp%环境变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM